Spring Cloud【Spring Security OAuth2 OSS logout 】单点登陆退出

导读

很久没有更新Spring Boot 系列文章了,这篇作为番外篇记录一下最近在使用Spring Security OAuth 登出的时候踩过的一些坑 及遇到的一些问题 期间查了许多资料 整理出了两种登出的方式

一. 通过SecurityContextLogoutHandler登出

In the client app (WebSecurityConfigurerAdapter):

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .logout()
            .logoutSuccessUrl("http://your-auth-server/exit");
}

In the authorization server:

@Controller
public class LogoutController {

    @RequestMapping("oauth/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        // token can be revoked here if needed
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            //sending back to client app
            response.sendRedirect(request.getHeader("referer"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二.通过tokenServices进行退出

In the authorization server:

@Autowired
ConsumerTokenServices tokenServices;
     
@GetMapping("/tokens/revoke/{tokenId:.*}")
@ResponseBody
public String revokeToken(@PathVariable String tokenId) {
    tokenServices.revokeToken(tokenId);
    return tokenId;
}

@FrameworkEndpoint
public class RevokeTokenEndpoint {

    @Autowired
    @Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;

    @DeleteMapping("/oauth/token")
    @ResponseBody
    public String revokeToken(String access_token) {
        if (consumerTokenServices.revokeToken(access_token)){
            return "注销成功";
        }else{
            return "注销失败";
        }
    }
}

退出时调用该接口

建议使用第一种

参考资料:

Spring Boot OAuth2 Single Sign Off (Logout)
Spring Security OAuth2 – Simple Token Revocation

你可能感兴趣的:(springcloud,springboot,oauth2.0,oss)