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?
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-refhere.