Ravi Kumar Ravanam Ravi Kumar Ravanam - 8 days ago 8
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.

spring-security.xml

<security:http auto-config="true">
<security:access-denied-handler error-page="/denied"/>
<security:form-login login-page="/login"
username-parameter="j_username"
password-parameter="j_password"
login-processing-url="/j_spring_security_check"
authentication-failure-url="/login?failed=true"
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 />
</security:http>


jsp

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

Answer

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