2014-02-24 132 views
7

在注销控制器中,我试着写了大量的代码组合。现在我有这个:如何在春季安全中撤销身份验证令牌?

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

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

SecurityContextHolder.getContext().setAuthentication(null); 
auth.setAuthenticated(false); 

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

我该怎么做?如何最终撤销令牌?

回答

9

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

Here是撤销令牌的控制器的示例,here带有 bean的oauth2配置。

+3

@raonirenosto,我遇到了使用您的示例自动装配Spring代理的问题。我必须将DefaultTokenServices更改为ConsumerTokenServices(这是一个接口)才能使用。但是,感谢您建议使用DefaultTokenServices.revokeToken()。 – vutbao

+0

自从我上次见到以来,Spring Oauth改变了许多课程。我猜这个框架比我写这个例子的时候更加稳定。 – raonirenosto

-2

自动装配的DefaultTokenServices然后使用此代码:

String authHeader = request.getHeader("Authorization"); 
String tokenValue = authHeader.replace("bearer", "").trim(); 
tokenService.revokeToken(tokenValue); 
tokenService.setAccessTokenValiditySeconds(1); 
tokenService.setRefreshTokenValiditySeconds(1); 

只要尝试代码撤销访问令牌。

+0

有人应该好心解释为什么这个答案是downvoted。为什么这不可取? – Olantobi

+0

@Olantobi因为以这种方式更改令牌有效性时间会更改整个应用程序的令牌有效性,而不仅仅是一个令牌。 – Mikk

1

如果需要撤销令牌为其他用户比当前的(例如管理员想要禁用用户帐户),您可以使用此:

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

随着tokenStore作为一个org.springframework.security.oauth2.provider.token.TokenStoreconsumerTokenServices感a org.springframework.security.oauth2.provider.token.ConsumerTokenServices

0

该线程有点老,但对于JWTToken用户来说这不起作用,因为令牌不存储。 所以另一种选择是使用过滤器。 1为管理员在数据库上锁定/解锁用户创建一个方法。 2使用的过滤器,如果该方法需要认证检查,如果用户是主动或不

为例:

@Override 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
    if(authentication != null 
      && authentication.getName() != null 
      && !authentication.getName().equalsIgnoreCase("anonymousUser")) { 
     UserModel user = userService.getUser(authentication.getName()); 
     if(user != null && !user.isActivated()) 
      throw new SecurityException("SECURITY_USER_DISABLED"); 
    } 
    chain.doFilter(request, response); 
} 

在客户端只拦截此错误并断开用户 希望这可以帮助别人。