Spring Security 3.0 Redirect to page that timed out

java, redirect, security, spring

Solution

You don't need to write any custom code since Spring Security can do that by default. Take a look to the documentation regarding `authentication-success-handler-ref` here.

authentication-success-handler-ref

This can be used as an alternative to default-target-url and always-use-default-target, giving you full control over the navigation flow after a successful authentication. The value should be the name of an AuthenticationSuccessHandler bean in the application context. By default, an implementation of SavedRequestAwareAuthenticationSuccessHandler is used and injected with the default-target-url.

Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with default-target-url (or always-use-default-target) as the implementation should always deal with navigation to the subsequent destination.

Problem

I am using Spring Security 3.0.6 and I would like to be able to do the following: If the user is a on a page and a session timeout occurs, the user will be taken to the log in page and on valid log in redirected back to the page the timeout occurred on. I currently have the following in my security.xml file. ``` <http auto-config="true" use-expressions="true"> <form-login login-page="/login" default-target-url="/main" always-use-default-target="false" authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="authenticationSuccessHandler" /> <remember-me/> <logout logout-success-url="/login" /> </http> ``` This is my authentication class: ``` public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { String url = ""; HttpSession session = request.getSession(false); if (session != null) { SavedRequest savedRequest = (SavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST); if (savedRequest != null) { url = savedRequest.getRedirectUrl(); } } System.out.println("url: "+ url); if (url == "") { response.sendRedirect(request.getContextPath()+"/main"); } else { response.sendRedirect(url); } } ``` } I send the user back to the log in page via javascript like: ``` window.location.href="/login"; ``` The url is always null in my authentication class. How can I make this work so Spring will redirect to the correct page?

Original source