春季 OAuth2 中的HMACSHA512不起作用



您可以帮助我使用我的代码吗?我正在尝试在我的网站上实现JWT身份验证的弹簧安全性OAuth2。我已经实现了oferizationserverconfig和resourceerverconfig,以及我声明了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一起使用吗?谢谢。

使您的算法更改为512您需要将服务器/资源设置为JWTACCESSTOKENCONVERTER SETVERIFIER与SetSigner所做的相同,例如:

jwtAccessTokenConverter.setVerifier(MacSigner("HMACSHA512", SecretKeySpec("secret_password".toByteArray(), "HMACSHA512")))

记住:两者都需要设置

我们可以通过添加java-jwt依赖项来实现HMACSHA_512算法。

maven依赖性

<dependency>
<groupid>com.auth0</groupid>
<artifactId>java-jwt</artifactId>
<version>3.8.0</version>
</dependency>

gradle依赖性

implementation 'com.auth0:java-jwt:3.8.0'

生成JWT令牌

步骤1:构建标头信息

Map<String, Object> map = new HashMap<String, Object>();
map.put("alg", "HS512");
map.put("typ", "JWT");

步骤2:构造关键信息

Algorithm algorithm = Algorithm.HMAC256("secret");  //secret key

步骤3:我们通过定义注册和自定义声明并结合标头和关键信息来生成JWT令牌

String token = JWT.create()
.withHeader(map)// Setting Header information 
.withIssuer("SERVICE")//Setting load signatures is who generates, for example, servers
.withSubject("this is test token")//Setting the theme of load signature
// .withNotBefore(new Date()) / / set the load definition before any time, and the jwt is not available.
.withAudience("APP")//Audiences who set payload signatures can also understand who accepts signatures
.withIssuedAt(nowDate) //Set the time when the payload generates the signature
.withExpiresAt(expireDate)//Setting the expiration time of load signature
.sign(algorithm);//Signature

最新更新