Custom Authentication Success Handler with Spring Security

I hope we now understand how Spring Security works. Additionally Custom Authentication Success Handler is another concept to serve your purpose of redirecting the users based on their roles. Having said this, it doesn’t mean that Custom Authentication Success Handler are just used for redirections. Another scenario might be where I want some user-specific session variables to set after authenticating the user, and probably then redirect the user to the respective page. So this adds to the flexibility of what can be done through Spring Security.

Let’s see how we can do that.

The Spring Security context file (spring-security.xml) will be like what we had seen in our previous Spring Security article.

Let’s now create our Custom Authentication Success Handler. Note the highlighted section in the code above, where we are referring to the customAuthenticationSuccessHandler bean. So where we have defined this bean? Here it is, in the mvc-dispatcher-servlet.xml.

Now the bean customAuthenticationSuccessHandler refers to a class com.jcombat.handler.CustomAuthenticationSuccessHandler, which we have already created. Below is the class the bean is referring to:

Note that the above customAuthenticationSuccessHandler must implement the AuthenticationSuccessHandler interface.


onAuthenticationSuccess is an interface method implementation which redirects the incoming request to the target URL based on the role or some other business parameter.

Also note that we have also set some user-specific session variables in our code, before redirecting the logged-in user to the target URL.

With our current code, logging-in with admin role redirects us to the admin page, while logging-in with the user role redirects me to the user page.

JSP files remain the same as we had written earlier for the previous Spring Security article. So you can navigate to our previous article on Spring Security by clicking here.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.