Customizing Spring security redirect after login
March 02, 2012 13:23:35 Last update: March 02, 2012 13:23:35
The landing page after login can be configured with the
An easy configuration looks like this:
But there are times that you want to do more initialization after login (such as loading user data), or apply more complex logic before redirecting. This is where the
This is a skeleton implementation:
default-target-url attribute of form-login. If a user was redirected to the login form after requesting a restricted URL, she's redirected to the original requested page after successful login.
An easy configuration looks like this:
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <http entry-point-ref="authProcessFilterEntryPoint" auto-config="true" access-decision-manager-ref="accessDecisionManager" use-expressions="true" lowercase-comparisons="true"> . . . <form-login login-page="/" login-processing-url="/authenticate" default-target-url="esbAuthSuccessHandler" authentication-failure-url="/"/> </http> </beans:beans>
But there are times that you want to do more initialization after login (such as loading user data), or apply more complex logic before redirecting. This is where the
authentication-success-handler-ref attribute comes into play. You create a class that implements org.springframework.security.web.authentication.AuthenticationSuccessHandler and use that as the authentication-success-handler-ref:
<http entry-point-ref="authProcessFilterEntryPoint" auto-config="true" access-decision-manager-ref="accessDecisionManager" use-expressions="true" lowercase-comparisons="true"> <form-login login-page="/" login-processing-url="/authenticate" authentication-success-handler-ref="myAuthSuccessHandler" authentication-failure-url="/"/> </http> <beans:bean id="myAuthSuccessHandler" class="com.example.security.MyAuthenticationSuccessHandler"/>
This is a skeleton implementation:
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException { // initialization logic after login . . . // redirect HttpSession session = request.getSession(); SavedRequest savedReq = (SavedRequest) session.getAttribute(WebAttributes.SAVED_REQUEST); if (savedReq == null) { response.sendRedirect(request.getContextPath() + "/landing"); } else { response.sendRedirect(savedReq.getRedirectUrl()); } } }