From your question, I see that you are trying to create your own logout, and also trying to use spring logout by default. I advise you to choose one method that does not mix them both. There are two ways to show you should exit spring:
First: default spring security exit
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID") .invalidateHttpSession(true)
In the above example, you only need to call URL /logout when you want to log out. There is no need to create @Controller to handle this output; instead, spring will help log the user out of the system. You can also add another thing that you want to cancel here.
Second: a programmatic exit
@RequestMapping(value = {"/logout"}, method = RequestMethod.POST) public String logoutDo(HttpServletRequest request,HttpServletResponse response){ HttpSession session= request.getSession(false); SecurityContextHolder.clearContext(); session= request.getSession(false); if(session != null) { session.invalidate(); } for(Cookie cookie : request.getCookies()) { cookie.setMaxAge(0); } return "logout"; }
If you use this output, you do not need to include the first method in the spring security configuration. Using this method, you can add additional actions to perform before and after logging off done.Btw, to use this logoff, just call the /logout URL and the user will log out manually. This method will invalidate the session, clear the spring security context and cookies.
Also, for the second method, if you use RequestMethod.POST , you need to include the csrf key as a message. An alternative way is to create a form with a csrf private input key. This is an example of using an automatic generated exit link with jquery:
$("#Logout").click(function(){ $form=$("<form>").attr({"action":"${pageContext.request.contextPath}"+"/logout","method":"post"}) .append($("<input>").attr({"type":"hidden","name":"${_csrf.parameterName}","value":"${_csrf.token}"})) $("#Logout").append($form); $form.submit(); });
You just need to create the <a id="Logout">Logout</a> hyperlink to use it.
If you use RequestMethod.GET , just include the csrf key as a parameter in your link, for example:
<a href="${pageContext.request.contextPath}/logout?${_csrf.parameterName}=${_csrf.token}">Logout</a>
That's all, I hope, his help.