有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

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

    Maven依赖

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

    梯度依赖

    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
    
  2. # 2 楼答案

    使您的算法更改为512 您需要将服务器/资源JwtAccessTokenConverter和setVerifier设置为与setSigner相同的功能,例如:

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

    记住:两者都需要设置