Spring Security custom interface logout

Spring Security custom interface logout

Use the Securityprovided tool to log out the user in the interface.

Tool code

	// 注入 tokenStore
	@Autowired
	private final TokenStore tokenStore;

	//在具体的业务代码中使用
	/**
	 * 删除 请求令牌 和 刷新令牌
	 * @param token 请求令牌
	 * @return 
	 */
	public Boolean removeToken(String token) {
    
    

		OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
		if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
    
    
		    // token 无效
			return false;
		}

		OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
		// 清空用户信息
		// CacheConstants.USER 为你的登录业务逻辑中的缓存 key
		cacheManager.getCache(CacheConstants.USER).evict(auth2Authentication.getName());

		// 清空access token
		tokenStore.removeAccessToken(accessToken);

		// 清空 refresh token
		OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
		tokenStore.removeRefreshToken(refreshToken);
		return true;
	}



use

	/**
     * 退出token
     *
     * @param authHeader Authorization
     */
    @DeleteMapping("/logout")
    public Res logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = true) String token) {
    
    
        if (StrUtil.isBlank(token)) {
    
    
           //退出失败,token 为空
           ...
        }

        String tokenValue = token.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
        removeToken(tokenValue);
        // 成功逻辑
    }

Guess you like

Origin blog.csdn.net/LitongZero/article/details/114973298