Spring Cloud【Spring Security OAuth2 OSS logout 】單點登錄退出

導讀

好久沒有更新Spring Boot 系列文章了,這篇做爲番外篇記錄一下最近在使用Spring Security OAuth 登出的時候踩過的一些坑 及遇到的一些問題 期間查了許多資料 整理出了兩種登出的方式spring

一. 經過SecurityContextLogoutHandler登出

In the client app (WebSecurityConfigurerAdapter):app

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

In the authorization server:ide

@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:spring-boot

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

code

@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 "註銷失敗";
        }
    }
}

退出時調用該接口server

建議使用第一種token

參考資料:

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

相關文章
相關標籤/搜索