Search This Blog

Saturday 19 October 2013

Logout Settings in Spring Security

We have seen how to configure login behavior for our application. How to let Spring manage authentication, session creation, authorization etc.The logical end to the flow would be to logout. A normal logout would involve releasing any resources, destroying sessions etc - and a logout page.
But with all our cookie lifecycle and session management being performed by Spring, it would be easy to let Spring manage the logout flow too.
Accordingly I created a simple signout page and named it "out.html"
The next step would be to tell Spring that on logout, my new HTML page should be displayed.
<http>
    <intercept-url pattern="/dynamic/**" access="ROLE_USER" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <form-login />
    <logout logout-success-url="/out.html" /> 
  </http>
We have specified here that when the logout action completes, the user should be redirected to out.html. But how do we initiate logout ?
Well you could put a sign out link on your page yes, but what should the URL be ? This is the logout fragment:
<p>
  <a href="${pageContext.request.contextPath}/j_spring_security_logout">Logout</a>
<p>
This action will evaluate to spring security's Logout Handler:
DEBUG SecurityContextLogoutHandler:62 - Invalidating session: 7F9505354369CE038BBA97918DC0518E
...
DEBUG SimpleUrlLogoutSuccessHandler:107 - Using default URL: /out.html
DEBUG DefaultRedirectStrategy:36 - Redirecting to '/FormLogin/out.html'
DEBUG HttpSessionSecurityContextRepository:127 - No HttpSession currently exists
As seen, Spring invalidated the HTTP Session. It then redirected the flow to the logout page specified. If we had remember-me option enabled than that cookie would also be removed. We can also have other cookies removed.
<logout logout-success-url="/out.html" delete-cookies="JSESSIONID" 
logout-url="/logout" invalidate-session="true" />
The delete-Cookies attribute can be used to do the same. For multiple cookies provided a comma separated list. Also if we want a custom logout url than we can specify one here. It will replace the 'j_spring_security_logout' url.

2 comments:

  1. Thank you very much!
    Very helpful for begginers like me :)

    ReplyDelete
  2. What happens if I provide a custom logout-url? Do I need to care for session cleanup and cookie handling in that case, or would Spring still apply its logout handler? Must the logout-url match with an existing page, or is it just the URL to invoke and spring will take care for the rest of it?
    Thank you very much!

    ReplyDelete