我有一个使用JWT和OAuth2的Spring Boot Rest API

使用Spring Security Starter的默认版本以及oauth2和jwt模块的Spring Boot 1.5.10。

在我的Authorization Server配置中,我根据本指南http://www.baeldung.com/spring-security-oauth-jwt声明自定义DefaultTokenServices

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Value("${tokenSigningKey:sdf8234kjdhgD}")
    private String tokenSigningKey;

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        CustomJwtAccessTokenConverter accessTokenConverter = new CustomJwtAccessTokenConverter();
        accessTokenConverter.setSigningKey(tokenSigningKey);
        return accessTokenConverter;
    }

    @Bean
    public TokenStore tokenStore() {
        return new CustomJwtJdbcTokenStore(accessTokenConverter(), dataSource);
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomAccessTokenEnhancer();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new CustomPasswordEncoder();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
        endpoints
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder());
        security.checkTokenAccess("isAuthenticated()");
    }

}


但是,实际使用的DefaultTokenServices是在AuthorizationServerEndpointsConfigurer幕后构建的那个

这是该类的相关代码

public AuthorizationServerTokenServices getDefaultAuthorizationServerTokenServices() {
        if (defaultTokenServices != null) {
            return defaultTokenServices;
        }
        this.defaultTokenServices = createDefaultTokenServices();
        return this.defaultTokenServices;
    }

    private DefaultTokenServices createDefaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(reuseRefreshToken);
        tokenServices.setClientDetailsService(clientDetailsService());
        tokenServices.setTokenEnhancer(tokenEnhancer());
        addUserDetailsService(tokenServices, this.userDetailsService);
        return tokenServices;
    }


我在线上遇到一个建议在DefaultTokenServices方法中设置public void configure(AuthorizationServerSecurityConfigurer security)的答案,但是当我这样做时确实使用了我的自定义bean,但是由于某种原因,它生成的令牌不是JWT格式,因此似乎在使用标记的默认简单格式。我只是不知道为什么它不使用我的自定义bean,因为在我遵循的指南中,它不是以这种方式声明的。有任何想法吗?

最佳答案

昨天我也发生了同样的事情。有效地,您需要将DefaultTokenServices添加到端点。之所以不采用JWT格式,是因为默认情况下未添加该格式。您需要将JWT格式bean添加到您的DefaultTokenServices中。

而且,您需要做的与AuthorizationServerEndpointsConfigurerDefaultTokenServices中生成createDefaultTokenServices()的操作大致相同,只是替换所需的细节。这是您需要添加到授权服务器配置中的相关代码:

@Bean
@Primary
public DefaultTokenServices tokenServices(TokenEnhancerChain tokenEnhancerChain, ClientDetailsService clientDetailsService) {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    defaultTokenServices.setSupportRefreshToken(true);
    defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);
    defaultTokenServices.setClientDetailsService(clientDetailsService);
    addUserDetailsService(defaultTokenServices,userDetailsService);
    return defaultTokenServices;
}

private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
    if (userDetailsService != null) {
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<PreAuthenticatedAuthenticationToken>(
                userDetailsService));
        tokenServices
                .setAuthenticationManager(new ProviderManager(Arrays.<AuthenticationProvider> asList(provider)));
    }
}


并将tokenServices方法添加到Authorization Server配置的configure方法中:

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
        endpoints
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenServices(tokenServices(tokenEnhancerChain,endpoints.getClientDetailsService()));
}


这对我有用。让我知道您是否遇到任何问题。

10-06 09:20