How to configure Resource Server in Spring Security for it to use additional information in JWT token

前端 未结 1 826
自闭症患者
自闭症患者 2021-02-08 01:41

I have an oauth2 jwt token server configured to set additional info about the user authorities.

@Configuration
@Component
public class CustomTokenEnhancer exten         


        
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 02:10

    In the following I'm referring to this Baeldung tutorial that I already implemented successfully: http://www.baeldung.com/spring-security-oauth-jwt

    First at all: The CustomTokenEnhancer is used on the AuthorizationServer side to enhance a created token with additional custom information. You should use the so called DefaultAccessTokenConverter on the ResourceServer side to extract these extra claims.

    You can @Autowire the CustomAccessTokenConverter into your ResourceServerConfiguration class and then set it to your JwtTokenStore() configuration.

    ResourceServerConfiguration:

    @Autowired
    private CustomAccessTokenConverter yourCustomAccessTokenConverter;
    
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }
    
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setAccessTokenConverter(yourCustomAccessTokenConverter);
        converter.setSigningKey(yourSigningKey);
        return converter;
    }
    

    The CustomAccessTokenConverter can be configured, so that the custom claims get extracted here.

    CustomAccessTokenConverter:

    @Component
    public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
    
        @Override
        public OAuth2Authentication extractAuthentication(Map claims) {
            OAuth2Authentication authentication = super.extractAuthentication(claims);
            authentication.setDetails(claims);
            return authentication;
        }
    
    }
    

    (see: https://github.com/Baeldung/spring-security-oauth/blob/master/oauth-resource-server-1/src/main/java/org/baeldung/config/CustomAccessTokenConverter.java )

    0 讨论(0)
提交回复
热议问题