1. Overview

This article explains about Spring security custom success or fails handler. Spring security provides complete customization on authentication success or fails handler. Spring security provide successHandler which has been called when authentication success and we can write custom code based on application requirement for example based on user role we can redirect the user to specific URL. In this example if user is admin then we will direct to /admin otherwise redirect to /home based on our business logic we can write our code.

2. Example

2.1 SecurityConfiguration

FormLoginConfigurer contains successHandler and failureHandler function which accepts custom handler for authentication success and failed. /login and /loginFailed has permission for all means to access those users do not require any authentication.

package com.javadeveloperzone;
import com.javadeveloperzone.controller.CustomAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by Java Developer Zone on 15-11-2017.
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired      // here is configuration related to spring boot basic authentication
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("zone").password("mypassword").roles("USER")
            .and()
            .withUser("zone2").password("mypassword").roles("ADMIN");// those are user name and password
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/loginFailed").permitAll().and().authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .successHandler(new CustomAuthenticationSuccessHandler())                 // On authentication success custom handler 
                .failureHandler(new CustomAuthenticationFailureHandler())                 // on authentication fail custom handler
                .loginPage("/login")
                .permitAll();
    }
}

2.2 CustomAuthenticationSuccessHandler

On authentication success, spring security will call onAuthenticationSuccess method in which we can write our custom code. Authentication object contains details related to a user who authenticate successfully.

Here we have create example based on user role redirect to a particulate landing page. If Role with ADMIN login then a user will redirect to /admin otherwise /home.

package com.javadeveloperzone;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
/**
 * Created by JavaDeveloperZone on 13-11-2017.
 * Spring Security will send control to AuthenticationSuccessHandler when authentication will get success
 */
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws
                                                                                                                                 IOException,
                                                                                                                                 ServletException {
        User principal = (User) authentication.getPrincipal();
        System.out.println("principal" + principal.getUsername());
        boolean isAdmin = false;
        Iterator<GrantedAuthority> grantedAuthorityIterator = principal.getAuthorities().iterator();
        while (grantedAuthorityIterator.hasNext()) {
            if (grantedAuthorityIterator.next().getAuthority().equalsIgnoreCase("ROLE_ADMIN")) {
                isAdmin = true;
            }
        }
        if (isAdmin) {
            response.sendRedirect("/admin");
        } else {
            response.sendRedirect("/home");
        }
    }
}

2.3 CustomAuthenticationFailureHandler

While use authentication will fail spring security give control to AuthenticationFailureHandler so we can write custom code to display proper message to user because of which reason user authentication failed. For example user has been locked, a user does not exist in the database those can be identify AuthenticationException type. AuthenticationException might LockedException (If user locked), UsernameNotFoundException (If user not found in our repository) and so many other exceptions are available to display a proper message to users.

package com.javadeveloperzone;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by JavaDeveloperZone on 13-11-2017.
 * Spring Security will send control to CustomAuthenticationFailureHandler when authentication will get failed
 */
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws
                                                                                                                             IOException,
                                                                                                                             ServletException {
        // write your custom code here
        response.sendRedirect("/loginFailed");
    }
}

3. References

Spring security document

4. Source Code

Spring security custom success or fail handler (82 KB)

 

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *