Spring Security 3.1 - Automatically redirect to lo

2019-03-29 23:46发布

问题:

I have a wenb applicatoin based on Spring and I am implementing Spring Security 3.1.

What I need is to be able to automatically redirect to login page, when the configured session-timeout occurs. I am implemting web pages containing a lot of jQuery functionality, so I need to be able to automatically redirect.

What currently happens, when the session-timeout passes, it's not until an action is performed - page submission that it redirects to the login page.

my spring-security.xml:

<http auto-config="true" disable-url-rewriting="true">
    <intercept-url pattern="/test/user*" access="ROLE_USER, ROLE_ADMIN"  />
    <intercept-url pattern="/test/admin" access="ROLE_ADMIN"  />
    <form-login login-page="/test/login" 
            default-target-url="/test/home" 
            authentication-failure-url="/test/loginfailed" />
    <logout invalidate-session="true" logout-success-url="/test/logout" />
    <!--
    <session-management invalid-session-url="/test/login">
        <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>
    </session-management>
    -->
</http> 

And in my web.xml I have:

<!-- Web Session Timeout (mins) --> 
<session-config> 
    <session-timeout>10</session-timeout> 
</session-config>   

回答1:

I don't think you will need to do it yourself, Spring pretty much handles this itself. That's the greatness of Spring!



回答2:

What I would TRY!! to do is something like this:

  • configure spring security in a way that it sends NOT an http status code 200 (OK) redirect (303/307) to login page but something else that can be detected by the ajax handler for example status code 401 (Unauthorized)
  • configure the ajax client in a way that it handles the 401 code (or what ever you use) correct, for example by showhing the log in page


回答3:

We have this scenario handled by setting the response status to 403. The following piece of code in our login.jsp does the trick:

<%
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
%>

Cons are, when you access the login page, the browser console would show that login request returned 403.

Once this is done, the ajax calls fails and goes to the failure state where you can check the status, show message that session is timed-out.