Spring OAuth2中的java HMACSHA512不工作
你能帮我写代码吗?我正试图在我的网站上为jwt身份验证在Spring Security中实现OAuth2。我已经实现了AuthorizationServerConfig和ResourceServerConfig,以及一些我声明了bean的SecurityConfig。其中一个bean是访问令牌转换器
以下是我的实现:
@Bean
@Primary
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigner(new MacSigner("HMACSHA512", new SecretKeySpec("secret_password".getBytes(), "HMACSHA512")));
return jwtAccessTokenConverter;
}
令牌已生成,但当我尝试使用此令牌调用某些api时,我在postman中遇到以下错误:
{
"error": "invalid_token",
"error_description": "Cannot convert access token to JSON"
}
当我替换此行时:
jwtAccessTokenConverter.setSigner(new MacSigner("HMACSHA512", new SecretKeySpec("secret_password".getBytes(), "HMACSHA512")));
这一行:
jwtAccessTokenConverter.setSigningKey("secret_password");
令牌生成和授权也可以工作。但它使用默认的HS256。你能告诉我如何修复我的代码来使用HS512吗?谢谢
# 1 楼答案
我们可以通过添加java jwt依赖项来实现HMACSHA_512算法
Maven依赖
梯度依赖
生成JWT令牌
步骤1:生成标题信息
步骤2:构造关键信息
步骤3:我们通过定义注册和自定义声明并结合头和密钥信息来生成jwt令牌
# 2 楼答案
使您的算法更改为512 您需要将服务器/资源JwtAccessTokenConverter和setVerifier设置为与setSigner相同的功能,例如:
记住:两者都需要设置