Hi i am writing JWT in Spring Boot using spring security. When i request POST on postman using below details in body section
{
"userName": "RAM",
"id":123,
"role": "admin"
}
then am getting below error
{
"timestamp": "2018-05-06T14:57:12.048+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.",
"path": "/token"
}
i used below code for jwt builder for generator
@Component
public class JwtGenerator {
public String generate(JwtUser jwtUser) {
// TODO Auto-generated method stub
Claims claim= Jwts.claims()
.setSubject(jwtUser.getUserName());
claim.put("userId", String.valueOf(jwtUser.getId()));
claim.put("role", jwtUser.getRole());
String secret = "YouTube";
byte[] bytesEncoded = Base64.getEncoder().encode(secret.getBytes());
return Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.ES512, secret).compact();
//With(SignatureAlgorithm.ES512, bytesEncoded).compact();
//signWith(SignatureAlgorithm.ES512,"YouTube").compact();
}
}
i used direct string value as secret key and 2 other possible combinations, but couldn't figure out the problem. i also provided the encode string as expected by DefaultJwtBuilder in JwtBuilder from below code, still no hit.
@Override
public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures. If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
return signWith(alg, bytes);
}
Any help would be really appreciated.
The signature algorithm in your code is ES512 which uses Elliptic Curve algorithm. Since you are using a secret key, you want to use an HMAC algorithm which has the prefix "HS". So HS256, HS384, or HS512.
ChangeJwts.builder().setClaims(claim).signWith(SignatureAlgorithm.ES512, secret).compact();
ToJwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With