Base64编码的密钥字节仅适用于HMAC签名。

7

你好,我正在使用Spring Security编写Spring Boot的JWT。当我在Postman上发送POST请求,并在body部分使用以下细节时:

{
"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 生成器的构建:
   @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();

    }

}

我曾经尝试过使用直接字符串值作为秘钥,并尝试了其他两种可能的组合,但仍然无法解决问题。我还按照以下代码中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);
    }

非常感谢您的帮助。

2个回答

28
您的代码中签名算法是ES512,它使用椭圆曲线算法。由于您正在使用秘密密钥,因此应该使用具有前缀“HS”的HMAC算法。因此,可选择HS256,HS384或HS512。
将代码更改为:
Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();

对我有用!这应该被标记为正确答案! - Big Zed
记得使用一个非常非常长的秘钥 ;) - gleitonfranco

0

你只需要用户名和密码,就可以从“SignatureAlgorithm.ES512, secret”切换到“SignatureAlgorithm.HS512, secret”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接