Search Tutorials


Spring Boot Security - Redirect to different pages after login using AuthenticationSuccessHandler Example | JavaInUse

Spring Boot Security - Redirect to different pages after Login using AuthenticationSuccessHandler Example

In a previous post we had implemented Spring Boot Security - Database Authentication.
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 page
Maven Project will be as follows-

boot-36_4
Add a new custom AuthenticationSuccessHandler which will do the redirection based on the roles. So the user javainuse will be redirected to the add new employee page while the user employee will be redirected to the welcome page on login.
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();
		}
	}

}




Finally modify the Spring Security configuration to autowire and use the custom AuthenticationSuccessHandler.
package com.javainuse.config;

import javax.sql.DataSource;

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.javainuse.handler.EmployeeAuthenticationSuccessHandler;

@Configuration
@EnableWebSecurity
public class EmployeeSecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	DataSource dataSource;

	@Autowired
	private EmployeeAuthenticationSuccessHandler successHandler;

	// Enable jdbc authentication
	@Autowired
	public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
		auth.jdbcAuthentication().dataSource(dataSource);
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/welcome").hasAnyRole("USER", "ADMIN")
				.antMatchers("/getEmployees").hasAnyRole("USER", "ADMIN").antMatchers("/addNewEmployee")
				.hasAnyRole("ADMIN").anyRequest().authenticated()
				.and().formLogin().successHandler(successHandler)
				.loginPage("/login").permitAll().and().logout().permitAll();

		http.csrf().disable();
	}

	// @Autowired
	// public void configureGlobal(AuthenticationManagerBuilder authenticationMgr)
	// throws Exception {
	// authenticationMgr.inMemoryAuthentication().withUser("admin").password("admin").authorities("ROLE_USER").and()
	// .withUser("javainuse").password("javainuse").authorities("ROLE_USER",
	// "ROLE_ADMIN");
	// }

}


These are the only changes required. Go to localhost:8080/welcome, we will be redirected to the custom login page.
boot-36_1
Enter the user javainuse and password javainuse, user is redirected to the add employee page.
boot-35_9
Enter the user employee and password employee, user is redirected to the welcome page.
boot-35_3

Download Source Code

Download it -
Spring Boot Security - Redirect using Authentication Handler