Ravi Kumar Ravanam Ravi Kumar Ravanam - 9 months ago 76
Java Question

logout is not working in spring security

I am writing a security application with spring security 4.0. As part of that I want to make a logout call. It is simply giving Request method 'POST' not supported.Here is my code.


<security:http auto-config="true">
<security:access-denied-handler error-page="/denied"/>
<security:form-login login-page="/login"
default-target-url="/home" always-use-default-target="true"/>
<security:custom-filter ref="secfilter" before="FILTER_SECURITY_INTERCEPTOR" />

<security:logout invalidate-session="true" logout-url="/j_spring_security_logout" logout-success-url="/login"/>
<!-- <security:logout logout-url="/j_spring_security_logout" logout-success-url="/login"/> -->

<security:csrf />


<a href="j_spring_security_logout"> <button class="logoutbtn">logout</button></a>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

Answer Source

I solve this problem in my project. The code as follows:

    @RequestMapping(value="/j_spring_security_logout", method = RequestMethod.GET)
    public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
            logger.info("logout ok");
        return "redirect";//You can redirect wherever you want, but generally it's a good practice to show login screen again.

I don't know whether you can accept this way. If you open CSRF´╝îyou must use post to request the logout url. In spring security4, the CSRF default open. This documents will give you more information. 18.5.3 Logging out 18.5.3 Logging Out