[英]How to revoke auth token in spring security?
在注銷控制器中,我試着編寫了很多代碼組合。 現在我有這個:
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
SecurityContextHolder.getContext().setAuthentication(null);
auth.setAuthenticated(false);
但提供的代碼執行令牌仍然有效。
我錯了什么? 如何最終撤銷令牌?
您正在尋找的類是DefaultServices
,方法是revokeToken(String tokenValue)
。
如果您需要為當前用戶之外的其他用戶撤消令牌(例如,管理員想要禁用用戶帳戶),您可以使用以下命令:
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.TokenStore
和consumerTokenServices
是org.springframework.security.oauth2.provider.token.ConsumerTokenServices
線程有點舊但是對於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);
}
在客戶端只是攔截此錯誤並斷開用戶希望這有助於某人。
使用DefaultTokenServices的當前授權用戶的令牌撤銷的簡單示例:
需要Bean用於默認令牌存儲
@Bean public DefaultTokenServices tokenServices() { DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; }
然后你可以編寫自己的控制器
@RestController @RequestMapping("/user") public class UserApi { @Autowired private DefaultTokenServices tokenServices; @Autowired private TokenStore tokenStore; @DeleteMapping("/logout") @ResponseStatus(HttpStatus.NO_CONTENT) public void revokeToken() { final OAuth2Authentication auth = (OAuth2Authentication) SecurityContextHolder .getContext().getAuthentication(); final String token = tokenStore.getAccessToken(auth).getValue(); tokenServices.revokeToken(token); } }
自動裝載DefaultTokenServices然后使用此代碼:
String authHeader = request.getHeader("Authorization");
String tokenValue = authHeader.replace("bearer", "").trim();
tokenService.revokeToken(tokenValue);
tokenService.setAccessTokenValiditySeconds(1);
tokenService.setRefreshTokenValiditySeconds(1);
只需嘗試代碼即可撤消訪問令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.