如何撤销spring security中的auth令牌?

gst*_*low 10 java spring spring-security-oauth2

在注销控制器中,我试着编写了很多代码组合.现在我有这个:

final Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if (auth != null) {
    new SecurityContextLogoutHandler().logout(request, response, auth);
}

SecurityContextHolder.getContext().setAuthentication(null);
auth.setAuthenticated(false);
Run Code Online (Sandbox Code Playgroud)

但提供的代码执行令牌仍然有效.

我错了什么?如何最终撤销令牌?

rao*_*sto 10

你正在寻找的课程是 DefaultServices方法revokeToken(String tokenValue).

这里是一个撤销令牌的控制器的例子,这里DefaultServicesbean 的oauth2配置.

  • 这两个链接都不存在了:( (7认同)
  • @raonirenosto,我遇到了使用Spring代理自动装配类的问题.我不得不将DefaultTokenServices更改为ConsumerTokenServices(这是一个接口)以使其工作.但感谢您建议使用DefaultTokenServices.revokeToken(). (4认同)

Wim*_*uwe 5

如果您需要撤销当前用户以外的其他用户的令牌(例如,管理员想要禁用用户帐户),则可以使用以下方法:

Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientIdAndUserName(
                                                           "my_oauth_client_id", 
                                                           user.getUsername());
for (OAuth2AccessToken token : tokens) {
  consumerTokenServices.revokeToken(token.getValue());
}
Run Code Online (Sandbox Code Playgroud)

tokenStore成为org.springframework.security.oauth2.provider.token.TokenStoreconsumerTokenServices成为org.springframework.security.oauth2.provider.token.ConsumerTokenServices