Spring Boot 无效的JWToken:kid是必需的JOSE标头

jxct1oxe  于 2022-12-12  发布在  Spring
关注(0)|答案(2)|浏览(264)

我正在尝试使用这个guide作为参考,用SpringBoot实现一个Oauth2授权服务器。
我的密钥库只有一个密钥。我已经成功地创建了一个JWToken(我可以在www.example.com上查看jwt.io)。
我还有一个测试资源服务器。当我尝试访问任何端点时,收到以下消息:

{
  "error": "invalid_token",
  "error_description": "Invalid JWT/JWS: kid is a required JOSE Header"
}

令牌确实没有子头,但我不知道如何添加它。我只能使用TokenEnchancer将数据添加到它的负载中。而且似乎我不是第一个with this issue
有没有办法添加这个头,或者至少在资源服务器上忽略它?

yc0p9oo0

yc0p9oo01#

我一直在写一篇文章,可能会对你有所帮助:https://www.baeldung.com/spring-security-oauth2-jws-jwk
因此,要配置Spring Security OAuth授权服务器以添加JWT kid 头,您可以按照4.9节中的步骤操作:
1.创建一个扩展 JwtAccessTokenConverter 的新类
1.在构造函数中:
1.使用您一直使用的相同方法配置父类
1.使用您正在使用的签名密钥获取 Signer 对象
1.重写encode方法。实现将与父实现相同,唯一的区别是在创建String标记时还要传递自定义头

public class JwtCustomHeadersAccessTokenConverter extends JwtAccessTokenConverter {

    private JsonParser objectMapper = JsonParserFactory.create();
    final RsaSigner signer;

    public JwtCustomHeadersAccessTokenConverter(KeyPair keyPair) {
        super();
        super.setKeyPair(keyPair);
        this.signer = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());
    }

    @Override
    protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        String content;
        try {
            content = this.objectMapper.formatMap(getAccessTokenConverter().convertAccessToken(accessToken, authentication));
        } catch (Exception ex) {
            throw new IllegalStateException("Cannot convert access token to JSON", ex);
        }
        Map<String, String> customHeaders = Collections.singletonMap("kid", "my_kid");
        String token = JwtHelper.encode(content, this.signer, this.customHeaders)
            .getEncoded();
        return token;
    }
}

1.然后,当然,使用这个转换器创建一个bean:

@Bean
public JwtAccessTokenConverter accessTokenConverter(KeyPair keyPair) {
    return new JwtCustomHeadersAccessTokenConverter(keyPair);
}

在这里,我使用了一个KeyPair示例来获取签名密钥并配置转换器(基于本文的示例),但是您可以根据自己的配置来修改它。
在本文中,我还解释了SpringSecurityOAuth身份验证服务器提供的相关端点。
另外,关于@ OrtomalaLokni的评论,我并不期望SpringSecurityOAuth在这一点上添加任何新特性。

nhn9ugyo

nhn9ugyo2#

我设法通过更改用于标识客户机将在其中检索pubkey的URL的参数来解决这个问题。
在www.example.com上application.properties,而不是:

security.oauth2.resource.jwk.key-set-uri=http://{auth_server}/.well-known/jwks.json

我用了:

security.oauth2.resource.jwt.key-uri=http://{auth_server}/oauth/token_key

如果我没理解错的话,key-set-uriconfig指向一个提供一组键的端点,并且需要一个kid。而key-uriconfig指向一个只有一个键的端点。

相关问题