Spring Custom AuthenticationSuccessHandler Example

In our previous post, we have created a Custom UserDetailsService that adds our own logic on how to retrieve user information. In this post, we will be creating a Custom AuthenticationSuccessHandler that will be called whenever the user successfully logged in. This assumes that you have already a working Spring MVC project. If not, you may want to consider reading this post on How to Create Spring MVC Project using Maven.

1.Add Spring Security in pom.xml

In your pom.xml, add dependency for spring security if you don’t have,

  
    <groupId>org.springframework.security</groupId>  
    <artifactId>spring-security-web</artifactId>  
    ${spring.security.version}  
  
  
  
    <groupId>org.springframework.security</groupId>  
    <artifactId>spring-security-core</artifactId>  
    ${spring.security.version}  
  
  
  
    <groupId>org.springframework.security</groupId>  
    <artifactId>spring-security-config</artifactId>  
    ${spring.security.version}  

and add spring security version in your properties section

  
     3.2.1.RELEASE  
 

2. Create your Custom AuthenticationSuccessHandler class

Create a new class that will implement AuthenticationSuccessHandler. Then add your logic on how you want to handle whenever the user successfully logs in. For this example, if ever the user successfully logs in, we will add his username and his roles to its session and redirect him to the home page.

CustomAuthenticationSuccessHandler.java

package com.javapointers.custom;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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 javax.servlet.http.HttpSession;
import java.io.IOException;

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //do some logic here if you want something to be done whenever
        //the user successfully logs in.

        HttpSession session = httpServletRequest.getSession();
        User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute("username", authUser.getUsername());
        session.setAttribute("authorities", authentication.getAuthorities());

        //set our response to OK status
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);

        //since we have created our custom success handler, its up to us to where
        //we will redirect the user after successfully login
        httpServletResponse.sendRedirect("home");
    }
}

3. Modify you applicationContext.xml

In your applicationContext.xml, create a new bean containing our Custom AuthenticationSuccessHandler class.

<bean id="customAuthenticationSuccessHandler" class="com.javapointers.custom.CustomAuthenticationSuccessHandler" />

Next, add our custom authenticationsuccesshandler bean to our form login or create a new form login entity if you don’t have one. form login is part of the http filter.


    <security:intercept-url pattern="/home" access="hasRole('ROLE_USER')" />
    <security:form-login login-page="/login" authentication-failure-url="/login?error=" authentication-success-handler-ref="customAuthenticationSuccessHandler" />
    <security:logout invalidate-session="true" logout-success-url="/logout" />

4. Testing our WebApp

When the user logs in, it should print the username and its roles in the home page. We have created 2 hard coded users in our applicationContext.xml with their respective roles.


    
        
            <security:user name="admin" password="password" authorities="ROLE_USER,ROLE_ADMIN" />
            <security:user name="user" password="password" authorities="ROLE_USER" />
        
    

custom authenticationsuccesshandler 1

custom authenticationsuccesshandler 2

Download Source Code Here!

Share this tutorial!
  • Jmp Jmp

    excellent…