我的Spring Boot应用程序中有以下配置:

@Configuration
public class SecurityConfig {

@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

@Configuration
@EnableAuthorizationServer
public static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private MyUserDetailsService userDetailsService;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    @Qualifier("myOauth2ClientDetailsService")
    private ClientDetailsService clientDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // set custom exception translator
        endpoints.exceptionTranslator(e -> {
            if (e instanceof OAuth2Exception) {
                OAuth2Exception exception = (OAuth2Exception) e;
                return ResponseEntity
                        .status(exception.getHttpErrorCode())
                        .body(new MyWLoginException(exception.getMessage()));
            } else {
                throw e;
            }
        });
        // other settings
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter()));
        endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService).tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain);
    }

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

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123");
        return converter;
    }

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

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

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-10)
public static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new AuditorFilter(), BasicAuthenticationFilter.class)
                .headers().frameOptions().disable()
             .and().csrf().disable()
             .authorizeRequests()
                .antMatchers("/img/**").permitAll()
                .anyRequest().authenticated();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer config) {
        config.tokenServices(tokenServices());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
        defaultAccessTokenConverter.setUserTokenConverter(userAuthenticationConverter());
        converter.setAccessTokenConverter(defaultAccessTokenConverter);
        converter.setSigningKey("123");
        return converter;
    }

    @Bean
    public UserAuthenticationConverter userAuthenticationConverter() {
        return new MyUserAuthenticationConverter();
    }

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


}

另外,我有一个特殊的端点来吊销令牌,该令牌通过以下方法处理请求:

@Autowired
private TokenStore tokenStore;
@Autowired
private AuthorizationServerTokenServices authorizationServerTokenServices;
@Autowired
private ResourceServerTokenServices resourceServerTokenServices;
...
final String tokenValue = ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getTokenValue();
        final OAuth2AccessToken token = tokenStore.readAccessToken(tokenValue);
        tokenStore.removeAccessToken(token);
        boolean authRemoved = ((DefaultTokenServices) authorizationServerTokenServices).revokeToken(tokenValue); // <- true
        boolean resourceRemoved = ((DefaultTokenServices) resourceServerTokenServices).revokeToken(tokenValue); // <- true
        SecurityContextHolder.getContext().setAuthentication(null);


没有任何错误。我看到令牌服务返回true(已删除)。但是,当我用旧的访问令牌调用任何终结点时,它的工作原理就像该令牌仍然有效。但是我从身份验证服务器和资源服务器上都删除了令牌。如何解决这个问题?

最佳答案

令牌吊销无法使用JWT进行,因为它所嵌入的令牌已过期。授权服务器发布后将不会捕获有关令牌的任何信息。因此,也许您应该尝试在授权服务器中使用JdbcTokenStore将令牌保存在数据库中,然后根据需要将其吊销(或者也可以将其保存在内存中)。如果您的应用程序分开,则可以使用RemoteTokenServices来验证令牌。

Here是一个教程,向您展示如何完成此操作。

关于java - Spring Security OAuth2吊销 token 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45917934/

10-09 03:18