Saturday, June 29, 2013

Why using Spring logout will redirect to session-timeout URL?

At first I have the most basic Spring security being configured in this way.
   <http auto-config="true">
        <intercept-url access="ROLE_ADMIN" pattern="/welcome*"/>
        <form-login authentication-failure-url="/loginfailed" default-target-url="/welcome" login-page="/login"/>
        <logout logout-success-url="/login"/>
   </http>
With this configuration, I can handle user login and logout request, where should the user land after successful login, and what will happen if the user failed to login. This is not enough, I want more. I would like to have a session control over the user. I want to stop the same user being login at the same time from different locations or different web browser. <session-management> could help me achieve this objective.
    <http auto-config="true">
        <intercept-url access="ROLE_ADMIN" pattern="/welcome*"/>
        <form-login authentication-failure-url="/loginfailed" default-target-url="/welcome" login-page="/login"/>
        <logout logout-success-url="/login"/>
        <session-management invalid-session-url="/sessionTimeout">
            <concurrency-control error-if-maximum-exceeded="true" max-sessions="1"/>
        </session-management>
    </http>
Anyhow, there is some problem with the code above, when I logout the application, it will redirect me to sessionTimeout page. Why this could happen? If I pay a close attention to the code, I could see that the problem is coming from <session-management invalid-session-url="/sessionTimeout">. Meanwhile, I've found something interesting in the code, by modifying the code as following will have my problem solved.
   <session-management>
      <concurrency-control error-if-maximum-exceeded="true" expired-url="/sessionTimeout" max-sessions="1"/>
   </session-management>
Now I know what is the real problem is happening. When a user logout, the session is first invalidate then only session management will get trigger. When session management come in, and found out the session has already gone, then sessionTimeout page will be redirect.

So if I want to stick to the invalid-session-url, I have to keep the session valid during logout. The code below showing details implementation.
   ...

   <logout invalidate-session="false" logout-success-url="/login"/>

   ...

No comments: