spring-boot - 只能为 HMAC 签名指定 Base64 编码的密钥字节
问题描述
嗨,我正在使用 Spring Security 在 Spring Boot 中编写 JWT。当我在正文部分使用以下详细信息向邮递员请求 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();
}
}
我使用直接字符串值作为密钥和其他两种可能的组合,但无法找出问题所在。我还从下面的代码中提供了 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,它使用椭圆曲线算法。由于您使用的是密钥,因此您希望使用前缀为“HS”的 HMAC 算法。所以 HS256、HS384 或 HS512。
改变
Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.ES512, secret).compact();
至
Jwts.builder().setClaims(claim).signWith(SignatureAlgorithm.HS512, secret).compact();
推荐阅读
- python - Python:从 a-Tag 获取下载链接,其中包含 onclick 生成的链接
- google-sheets - 如何使用两个条件对范围中的值进行求和,同时在 Google 表格中使用 OR 条件
- vba - 我的拆分访问数据库为其他用户进行查询更改
- r - County R中同一列中相同单词的频率
- jena - 无法让 Apache Jena 解析器从 json-ld 文件中获取 @id
- c# - 如何知道哪个 Id 属于哪个对象?
- html - 我正在尝试将 HTML 代码用作列表样式类型
- c++ - 关于 c ++ 中连接的良好做法:使用函数还是字符串流?
- http - 使用 dio 发布调用 api 会产生 404 抖动
- php - 当用户在codeigniter中发送电子邮件时,我想将图像路径存储在带有索引的数组中