首页 > 解决方案 > Spring sercurity中的自定义JWT响应

问题描述

我使用 API oauth/token 在 spring sercurity oauth2 中获取 JWT 令牌。我尝试通过使用 TokenEnhancer 接口的增强方法 ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo) 在响应中添加一些附加信息。但是这些附加信息也添加到了 JWT 中,所以它太大了。有没有办法将附加信息添加到 oauth/token 请求的正文中,但不是在 JWT 中。

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    final Map<String, Object> additionalInfo = new HashMap<>();
    WebUser webUser = (WebUser) authentication.getUserAuthentication().getPrincipal();
    additionalInfo.put("user_name", authentication.getName());
    additionalInfo.put("roles", authentication.getAuthorities());
    if(webUser.getFunctions() != null) {
        additionalInfo.put("functions",  webUser.getFunctions().toString());
    }else {
        additionalInfo.put("functions",  null);
    }

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    return accessToken;
}

标签: oauth-2.0jwtspring-security-oauth2

解决方案


当您修改令牌时,在 Spring 上下文中称为“增强令牌”。从逻辑上讲,您应该首先将令牌转换为 JWT,然后添加其他属性,这样它们就不会影响您的 JWT 有效负载。

这是我使用 Spring Boot 构建的项目中的一个片段

 @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(
                Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenEnhancer(tokenEnhancerChain)
                .accessTokenConverter(jwtAccessTokenConverter())
                .tokenStore(tokenStore());
    }

在这里,我使用tokenEnhancer()向我的令牌添加了一些属性,然后使用jwtAccessTokenEnhancer(). 如果我在这里颠倒顺序,我会得到你想要的。


推荐阅读