Spring Boot Security - Redirect to different pages after Login using AuthenticationSuccessHandler Example
In some scenarios we might want to redirect different users to different pages depending on the roles assigned to the users.
For example we might want users with role USER to be redirected to the welcome page, while users with role ADMIN to be redirected to the add employee page.
We will be making use of the AuthenticationSuccessHandler.
Spring Boot Security - Table Of Contents
Spring Boot + Simple Security Configuration Spring Boot Form Security Login Hello World Example Spring Boot Security - Custom Login Page Example Spring Boot Security - JDBC Authentication Example Spring Boot Security - Creating Users Programmatically Using JdbcUserDetailsManager Spring Boot Security - Password Encoding Using Bcrypt Spring Boot Security - Enabling CSRF Protection Spring Boot Security - Authentication Handler Example
Lets Begin-
We will be modifying the code we developed in the previous Spring Boot Security - Creating a custom login pageMaven Project will be as follows-
package com.javainuse.handler; import java.io.IOException; import java.util.Collection; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; @Component public class EmployeeAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication authentication) throws IOException, ServletException { boolean hasUserRole = false; boolean hasAdminRole = false; Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority grantedAuthority : authorities) { if (grantedAuthority.getAuthority().equals("ROLE_USER")) { hasUserRole = true; break; } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { hasAdminRole = true; break; } } if (hasUserRole) { redirectStrategy.sendRedirect(arg0, arg1, "/welcome"); } else if (hasAdminRole) { redirectStrategy.sendRedirect(arg0, arg1, "/addNewEmployee"); } else { throw new IllegalStateException(); } } }