gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
I'm using io.jsonwebtoken:jjwt-api. In new version, the code:return Jwts .builder()…
- User
I'm using io.jsonwebtoken:jjwt-api. In new version, the code:return Jwts .builder() .claims(extraClaims) .subject(userDetails.getUsername()) .issuedAt(new Date()) .expiration(new Date(System.currentTimeMillis() + expiration)) .signWith(getSignInKey(), SignatureAlgorithm.HS256) .compact(); The signWith is Deprecated. How to fix it?
- Assistant
In recent versions of
jjwt(specifically from 0.11.x and above), thesignWithmethod that takes aKeyandSignatureAlgorithmsignature algorithm is deprecated. Instead, the recommended usage is:- You provide the signing key already typed to the right key type (for example, an HMAC key is a
SecretKey). - You call
signWith(Key key)without specifying the algorithm because the algorithm will be inferred from the key type.
How to fix your code
Suppose you currently have something like this for your key:
private Key getSignInKey() { byte[] keyBytes = Decoders.BASE64.decode(secret); return Keys.hmacShaKeyFor(keyBytes); }Then you can just update your builder code to:
return Jwts.builder() .setClaims(extraClaims) .setSubject(userDetails.getUsername()) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expiration)) .signWith(getSignInKey()) // no SignatureAlgorithm here .compact();
Explanation
- You no longer need to specify
SignatureAlgorithm.HS256explicitly. - The algorithm is inferred automatically from the provided key instance.
- Make sure that
getSignInKey()returns a properjava.security.Key, such as fromKeys.hmacShaKeyFor(...).
Example in full
import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; import java.security.Key; import java.util.Date; import java.util.Map; public class JwtUtil { private String secret = "your-256-bit-secret-your-256-bit-secret"; // at least 256 bit key private Key getSignInKey() { byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8); return Keys.hmacShaKeyFor(keyBytes); } public String generateToken(Map<String, Object> extraClaims, String username, long expiration) { return Jwts.builder() .setClaims(extraClaims) .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + expiration)) .signWith(getSignInKey()) // No SignatureAlgorithm param .compact(); } }
Summary
- Remove the
SignatureAlgorithmparam fromsignWith. - Ensure the signing key is properly created with the key factory method (like
Keys.hmacShaKeyFor). - This is a breaking change from older jjwt versions.
If you want, I can help you adapt the full code for the latest jjwt version!
- You provide the signing key already typed to the right key type (for example, an HMAC key is a