尝试解码Jwt时出现错误:被拒绝的已签名JWT:期望使用另一种算法或找不到匹配的密钥。

11

我正在尝试使用与spring security集成的ForgeRock OpenAM设置OAuth2-OpenID Connect,但是出现以下错误

2019-06-17 15:01:42.576 DEBUG 62255 --- [nio-8090-exec-2] .o.s.r.w.BearerTokenAuthenticationFilter : 
Authentication request for failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException: 
An error occurred while attempting to decode the Jwt: 
Signed JWT rejected: Another algorithm expected, or no matching key(s) found

Jwk .well-known uri返回以下支持的算法:
"id_token_signing_alg_values_supported": [
    "PS384",
    "ES384",
    "RS384",
    "HS256",
    "HS512",
    "ES256",
    "RS256",
    "HS384",
    "ES512",
    "PS256",
    "PS512",
    "RS512"
  ]

解码后的JWT显示以下标头:
{
  "typ": "JWT",
  "zip": "NONE",
  "alg": "HS256"
}

有没有一种方法可以根据标头中的值设置特定的JwtDecoder,或强制AM使用特定的算法?
4个回答

8
问题在于令牌加密中访问管理的配置。它是空的,但由于某种原因JWT标头显示为HS256,这导致Spring查找HS256私钥并失败。更改设置以使用RS256后,一切开始正常运作。

3
对于 KeyCloak 10.0.1 版本,需要在“领域/令牌”下进行类似的设置,将“默认签名算法”设置为 RS256(或您喜欢的其他算法)。 - meDev

6

在我的情况下,NimbusJwtDecoder默认采用RS256作为JwsAlgo。因此我配置了JWTDecoder并提供了在我的JWT头中发现的RS512算法。

{ "alg": "RS512", "typ": "JWT" }

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    private String jwkSetUri;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().oauth2ResourceServer().jwt().decoder(jwtDecoder());
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm(SignatureAlgorithm.RS512).build();
    }
}

1

3
谢谢Bernhard,但是密钥已经存在。OIDC是OAuth2的扩展,所以我不会说它们完全是不同的主题。 - Adnan Mamajiwala

0
另一种导致此类错误的方式是在身份验证路径上存在JWT URI不一致。
例如,JWT发行者URI可能已在服务器端硬编码为特定区域或用户池,例如"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abcdefghi"。
在使用硬编码值时要小心。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接