Redirect user to login page on timeout Spring Secu

2019-08-03 01:13发布

问题:

I am using Spring Core version 4.1.6 and Spring security 4.0.1.

I want to redirect user to login page on timeout.

So far after some research, I implemented ApplicationListener<HttpSessionDestroyedEvent> and I can now successfully intercept timeouts and logouts.

I have HttpSessionDestroyedEvent object in onApplicationEvent function. This object dont seem to have any method from where I can redirect user or return login model object. My question is how can I redirect user to login page?

I have seen this url but it doesn't intercepts timeouts. My question is more focused towards timeouts.

回答1:

There are several approaches for this. first you can use spring security auto config in your applicationContext.xml by setting login-page it will automatically redirect not logged-in users reaching secured routes (like /userReged/**) to that certain login-page :

<security:http auto-config="true">
    <security:intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
    <security:intercept-url pattern="/userReged/**" access="ROLE_USER"/>
    <security:form-login
            login-page="/"
            default-target-url="/somePage"
            authentication-failure-url="/user/logfailed?error"
            username-parameter="userName"
            password-parameter="userPassword" />
    <security:logout
            logout-success-url="/?logout"/>
</security:http>

one other way is to check user being logged-in in your controller manually in specific route :

@RequestMapping("/somePage")
public String getSomePage(Model model, HttpServletRequest request) {

    Principal principal = request.getUserPrincipal();
    if (principal != null) {

        User activeUser = userService.getUserByPhone(principal.getName());
        // ...

    } else { // user is not authenticated
        System.out.println("user is not authenticated to proceed the somePage!!!!!!!");
        return "redirect:/";
    }
}

In order to set timeout for spring security you can put this in your web.xml :

<session-config>
    <session-timeout>
        1440
        <!--mins-->
    </session-timeout>
</session-config>

now if you want to redirect clients on exact timeout you can refresh the page automatically in client side in some intervals.