Spring Security : Redirect to different pages after Login


In this tutorial we'll learn how to redirect a user after authentication to a different pages dependent on role using spring security.

1. Spring security configuration
Spring Security provides an AuthenticationSuccessHandler component that has the responsibility of deciding what to do after a successful authentication.

<http use-expressions="true" >
        <intercept-url pattern="/login*" access="permitAll" />
        <intercept-url pattern="/**" access="isAuthenticated()" />

        <form-login login-page='/login.html'
            authentication-failure-url="/login.html?error=true"
            authentication-success-handler-ref="myAuthSuccessHandler"/>

        <logout/>
    </http>

    <beans:bean id="myAuthenticationSuccessHandler"
        class="com.security.MySimpleUrlAuthSuccessHandler" />


2. The Authentication Success Handler
public class MySimpleUrlAuthSuccessHandler implements AuthenticationSuccessHandler {
    protected Log logger = LogFactory.getLog(this.getClass());
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication) throws IOException {
        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }
    protected void handle(HttpServletRequest request,
      HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);
        if (response.isCommitted()) {
            logger.debug("Response has already been committed. Unable to redirect to "                                                        + targetUrl);
            return;
        }
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }
    protected String determineTargetUrl(Authentication authentication) {
        boolean isUser = false;
        boolean isAdmin = false;
        Collection<? extends GrantedAuthority> authorities =                        
                                                    authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
                isUser = true;
                break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            }
        }
        if (isUser) {
            return "/userpage.html";
        } else if (isAdmin) {
            return "/adminpage.html";
        } else {
            throw new IllegalStateException();
        }
    }
    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }
    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}
  • The determineTargetUrl function decides where to redirect user after login