2014-02-24 136 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); 
} 

在客戶端只攔截此錯誤並斷開用戶 希望這可以幫助別人。