Spring Security OAuth2 token存储Redis用户登出logOut

Redis用户登出有两种方案,一种是通过资源服务器配置logoutSuccessHandler处理函数,并实现LogoutSuccessHandler接口来处理退出用户;
另外一种是自定义封装接口,通过RedisTokenStore来删除用户信息的形式;

通过资源服务器或认证服务器配置的方式

  • WebSecurityConfigurerAdapter配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth_user/*").denyAll()
.antMatchers("/oauth2/**", "/oauth/**").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.and()
.csrf().disable();

}
  • 退出成功处理LogoutSuccessHandler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @Description: 用户成功退出
* @Package: cn.appblog.security.handler.AjaxLogoutSuccessHandler
* @Version: 1.0
*/
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {
@Autowired
private TokenStore tokenStore;

@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String accessToken = request.getParameter("access_token");
if (StringUtils.isNotBlank(accessToken)) {
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(accessToken);
if (oAuth2AccessToken != null) {
System.out.println("access_token: " + oAuth2AccessToken.getValue());
tokenStore.removeAccessToken(oAuth2AccessToken);
OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
tokenStore.removeRefreshToken(oAuth2RefreshToken);
tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
}
}
HttpUtils.writeSuccess(BaseResponse.createResponse(HttpStatusMsg.OK.getStatus(), "退出成功"), response);
}
}

访问:http://127.0.0.1:9003/logout?access_token=0decd3ef67804618bfb87d7b99f1d3ad

1
2
3
4
{
"status": 200,
"message": "退出成功"
}

自定义退出接口方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 账号退出
*/
@RequestMapping(value = "logout", method = RequestMethod.POST)
public ResponseEntity<BaseResponse> logOut(String access_token) {
if (StringUtils.isNotBlank(access_token)) {
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(access_token);
if (oAuth2AccessToken != null) {
System.out.println("access_token: " + oAuth2AccessToken.getValue());
tokenStore.removeAccessToken(oAuth2AccessToken);
OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
tokenStore.removeRefreshToken(oAuth2RefreshToken);
tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
}
}
return ResponseEntity.ok(BaseResponse.createResponse(HttpStatusMsg.OK));
}

POST访问:http://127.0.0.1:9003/oauth2/logout
参数:access_token

1
2
3
4
{
"status": 200,
"message": "SUCCESS"
}

本文转载参考 原文 并加以调试

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :