【问题标题】:HMACSHA512 in Spring OAuth2 doesn't workSpring OAuth2 中的 HMACSHA512 不起作用
【发布时间】:2018-07-17 16:33:13
【问题描述】:

你能帮我写代码吗?我正在尝试在 Spring Security 中实现 OAuth2 以在我的网站上进行 jwt 身份验证。我已经实现了 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 时,我在邮递员中收到此错误:

{
    "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 吗?谢谢。

【问题讨论】:

  • @dur 我也尝试了你的第二个建议,我使用这个新的 MacSigner("HMACSHA512", new SecretKeySpec("secret_password".getBytes(), "HMACSHA512")) 作为新变量并将其设置为签名者和验证者,我认为它有效:) 但只是额外的问题......如果它是一个好的程序?
  • 为什么你认为这不是一个好的程序?
  • 顺便说一句:我已经回答了你的问题here。您是否认为,您的新问题与旧问题重复?如果您愿意,我可以将您的(现在工作的代码)复制到我的答案中。我没有添加一些代码,因为我还不能测试它。

标签: java spring spring-security spring-security-oauth2 hmac


【解决方案1】:

我们可以通过添加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");

第二步:构造关键信息

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

第三步:我们通过定义注册和自定义声明,结合header和key信息生成jwt token

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】:

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

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

    记住:两者都需要设置

    【讨论】:

      猜你喜欢
      • 2018-09-24
      • 2020-10-20
      • 2014-07-27
      • 1970-01-01
      • 2017-01-13
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      相关资源
      最近更新 更多