嗨,我正在使用 spring 安全性在 Spring Boot 中编写 JWT。当我使用正文部分中的以下详细信息向 postman 请求 POST 时
{
"userName": "RAM",
"id":123,
"role": "admin"
}
然后我得到低于错误
{
"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"
}
我使用以下代码用于生成器的 jwt builder
@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();
}
}
我使用直接字符串值作为 key 和 2 个其他可能的组合,但无法找出问题所在。我还在 JwtBuilder 中从下面的代码中提供了 DefaultJwtBuilder 预期的编码字符串,仍然没有命中。
@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);
}
任何帮助将非常感激。
最佳答案
您代码中的签名算法是 ES512,它使用椭圆曲线算法。由于您使用的是 key ,因此您希望使用前缀为“HS”的 HMAC 算法。所以 HS256、HS384 或 HS512。
改变Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.ES512, secret).compact();
到Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();
关于spring-boot - 只能为 HMAC 签名指定 Base64 编码的 key 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201237/