Moh*_*wal 5 base64 spring-security jwt spring-boot
嗨,我正在使用 spring 安全性在 Spring Boot 中编写 JWT。当我使用正文部分中的以下详细信息向邮递员请求 POST 时
{
"userName": "RAM",
"id":123,
"role": "admin"
}
Run Code Online (Sandbox Code Playgroud)
然后我得到低于错误
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码用于生成器的 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();
}
}
Run Code Online (Sandbox Code Playgroud)
我使用直接字符串值作为密钥和 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);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
小智 16
您代码中的签名算法是 ES512,它使用椭圆曲线算法。由于您使用的是密钥,因此您希望使用前缀为“HS”的 HMAC 算法。所以 HS256、HS384 或 HS512。
改变
Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.ES512, secret).compact();
到
Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();
| 归档时间: |
|
| 查看次数: |
7411 次 |
| 最近记录: |