how to correctly logout user in spring security

Viewed 24270

Edit - 1

<security:logout
    invalidate-session="true"
    logout-success-url="/logout"
    logout-url="/logoutfail"/>

 </security:http>

Edit - 1 end http://pastie.org/8588538 are the lines 1 to 6 a correct way to logout users? because when I do, the user seems to be logged out momentarily on the page but then can visit other pages again with the same login. it seems line 31 and 38 is making a new session cookie. but how?

@RequestMapping(value = "/logout" )
    public String logout(ModelMap model, HttpServletRequest request){
        request.getSession(true).invalidate();
        System.out.println("logout user page shown--------------------");
        return "/login/logout";       
   }


200 OK

GET /logout

200 OK

localhost:8080

5.7 KB

127.0.0.1:8080



225ms
HeadersResponseHTMLCacheCookies
Response Headersview source
Content-Language    en
Content-Length  5864
Content-Type    text/html;charset=ISO-8859-1
Date    Mon, 30 Dec 2013 21:38:59 GMT
Server  Apache-Coyote/1.1
Set-Cookie  JSESSIONID=4B961D14E4B3096368BCC5F9A55874BC; Path=/ttmaven/; HttpOnly

Request Headersview source
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  JSESSIONID=A0E89C909D0A7F7BE93EC737130E9A31
Host    localhost:8080
Referer http://localhost:8080/ttmaven/users/home
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0
3 Answers

HTML Page

<li><a href="#" th:href="@{/logout}"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>

We just need to map this /logout link in our controller.

@RequestMapping(value="/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);
    }
    return "redirect:/login?logout"; //You can redirect wherever you want, but generally it's a good practice to show login screen again.
}
Related