spring security+oauth2退出登录(二)-token过期后退出登录

代码详细

expireLogout

/logout/expirePage接口使用thymeleaf跳转到expire-logout.html页面

@Controller
public class LogoutController {

    /**
     * 过期退出登录
     * 
     * @param clientId
     * @param accessToken
     * @return
     */
    @GetMapping("/logout/expirePage")
    public ModelAndView expireLogout(String clientId, String accessToken) {
        Map<String, String> data = new HashMap<String, String>();
        data.put("clientId", clientId);
        return new ModelAndView("/expire-logout", data);
    }
}

expire-logout.html

expire-logout.html不进行显示 只为了跳转到后台域 清除session 执行两个逻辑 1:调用/logoutSession 清除session

                                                                                                                            2:获取授权码 重新跳转到登录页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue模板</title>
    <!--<link rel="stylesheet" type="text/css" media="all" href="/css/element.css" th:href="@{/css/element.css}"/>-->
    <script type="text/javascript" src="../js/vue2.6.8.min.js" th:src="@{/js/vue2.6.8.min.js}"></script>
    <!--<script type="text/javascript" src="../js/element.js" th:src="@{/js/element.js}"></script>-->
    <script type="text/javascript" src="../js/axios.min.js" th:src="@{/js/axios.min.js}"></script>
    <script type="text/javascript" src="../js/httpConfig.js" th:src="@{/js/httpConfig.js}"></script>
    <style type="text/css">
        body {
            font-family: "微软雅黑";
        }

        .meveBox p {
            margin: 0;
            margin-left: 8px;
            padding: 0;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div id="app">
    <div id="test">
    </div>
</div>
</body>
<script th:inline="javascript">
    new Vue({
        el: '#app',
        data: {},
        created() {
            this.authorize()
        },
        mounted() {
        },
        methods: {
            authorize() {
                var clientId = [[${clientId}]]
                var getCookie = this.getCookie("JSESSIONID")
                axios.request({
                    method: 'get',
                    url: serveHttp + '/oauth/logoutSession',
                    headers: {
                        'Content-Type': 'application/json',
                        'Cookie': getCookie
                    }
                }).then(function (res) {
                    console.log("--------" + res);
                    window.location.href = serveHttp + "/oauth/authorize?client_id=" + clientId + "&response_type=code"

                })
                    .catch(function (error) {
                    })
            },
            //获取cookie
            getCookie: function (cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1);
                    if (c.indexOf(name) != -1) {
                        return c.substring(name.length, c.length);
                    }
                }
                return "";
            },
        }
    })
</script>
</html>

logoutSession

在token过期时 虽然不能访问后台接口 但是因为登录状态是cookie与session判断 且没有失效 如果不清空session 在获取授权码时就不会跳转到login页面 所以 我们需要清空session 使获取授权码时跳转

同时因为前后端分离项目 各自的域都不同 自由跳转到后台域上才能清空session 这就是expire-logout.html存在的意思

@RestController
@RequestMapping("/oauth")
public class OauthController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    @Lazy
    private TokenStore tokenStore;

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    Utils utils;


    /**
     * token过期清除session 保证跳页
     * 
     * @return
     * @throws IOException
     */
    @GetMapping("/logoutSession")
    public void logoutSession() throws IOException {
        RequestAttributes requsetAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletResponse response = ((ServletRequestAttributes)requsetAttributes).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes)requsetAttributes).getRequest();
        // 清除cookie
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setMaxAge(0);
        cookie.setPath("/authentication");
        response.addCookie(cookie);
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        Result result = new Result(200, "退出登录成功");
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }

}

 

猜你喜欢

转载自blog.csdn.net/qq_20143059/article/details/113771961