Redirect to Different Pages after Login based on User Roles – Spring Boot Security

In the real-life scenario, most software applications work with user-based authentication. When the user accesses the website url in the Spring boot application, the user is redirected to the authentication login page. After successful login, the user is redirected to different dashboard based on logged in user roles.

In this article, we’ll see how to create a login page to authenticate and link to different user role-based dashboard pages.



Step 1 – Configure Security dependency

Create a spring boot application and configure spring security dependency in pom.xml. Add web application dependency to run tomcat server. The security module will allow to configure user roles based redirection.

The pom.xml below contains all of the required dependency.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.4.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>Spring-Application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootSecuritySimple</name>
	<description>Spring Boot Project</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>


Step 2 – Add User and Admin Dashboard jsp files

The spring boot application runs on tomcat server. Add the jsp configurations in application.properties file.

Add login.jsp to login authentication page. Add two dashboard jsp files, say userDashboard.jsp and adminDashboard.jsp. Upon successful login, the security module will be redirected to any of the jsp dashboard pages.

application.properties

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

src/main/webapp/WEB-INF/jsp/login.jsp

<center>
<h1>Welcome to Spring Boot Security</h1>

<form method="POST" action="/login">
	User Name : <input type="text" name="username" value="user"/><br><br>
	Password  : <input type="password" name="password" value="password"/><br><br>
	<input type="submit" name="submit"/>
</form>
</center>

src/main/webapp/WEB-INF/jsp/userdashboard.jsp

<center>
<h1>Welcome to Spring Boot User DashBoard</h1>

<h2>You are in Spring Boot User DashBoard Page</h2>
<br><a href="/logout">logout</a>
</center>

src/main/webapp/WEB-INF/jsp/admindashboard.jsp

<center>
<h1>Welcome to Spring Boot Admin DashBoard</h1>

<h2>You are in Spring Boot Admin DashBoard Page</h2>
<br><a href="/logout">logout</a>
</center>


Step 3 – Configure Controller class for jsp files

Create a controller class that redirects your urls to the respective jsp files. Add 3 urls to the controller class. The “/login” url will render the.jsp login page. The “/userDashboard” url will display the “userdashboard.jsp” page. If the user role is “ROLE USER,” the login page will be redirected to the user dashboard page. “/adminDashboard” url will display the “admindashboard.jsp” page. If the logged in user role is “ROLE_ADMIN”, the user will be redirected to the admin dashboard page.

TestController.java

package com.yawintutor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping
public class TestController {

	@RequestMapping("/login")
	public ModelAndView login() {
		return new ModelAndView("login");
	}

	@RequestMapping("/userDashboard")
	public ModelAndView userDashboard() {
		return new ModelAndView("userdashboard");
	}

	@RequestMapping("/adminDashboard")
	public ModelAndView adminDashboard() {
		return new ModelAndView("admindashboard");
	}
}


Step 4 – Spring Boot Security configuration

The user-based redirect is configured using the customized Success Handler for spring boot security. Create a Custom Success Handler class with AuthenticationSuccessHandler. The AuthenticationSuccessHandler interface will be called for successful login authentication. Add the logic to redirect the user’s role to the respective dashboard pages.

The following code is a sample implementation of the AuthenticationSuccessHandler interface.

CustomSuccessHandler.java

package com.yawintutor;

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.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {

		String redirectUrl = null;

		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
		for (GrantedAuthority grantedAuthority : authorities) {
			System.out.println("role " + grantedAuthority.getAuthority());
			if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
				redirectUrl = "/userDashboard";
				break;
			} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
				redirectUrl = "/adminDashboard";
				break;
			}
		}
		System.out.println("redirectUrl " + redirectUrl);
		if (redirectUrl == null) {
			throw new IllegalStateException();
		}
		new DefaultRedirectStrategy().sendRedirect(request, response, redirectUrl);
	}
}

Create a Spring Boot Security Configuration class by extending the SpringBootSecurityConfiguration class. Create an auto-wired class object reference for the AuthenticationSuccessHandler interface. Use the AuthenticationSuccessHandler object to validate the security configuration.

SpringBootSecurityConfiguration.java

package com.yawintutor;

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.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
public class SpringBootSecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	@Autowired
	AuthenticationSuccessHandler successHandler;
	
	@Override
	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("user").password("{noop}password").roles("USER")
			.and()
			.withUser("admin").password("{noop}password").roles("ADMIN");
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http
			.csrf().disable()
			.authorizeRequests()
			.antMatchers("/user").hasAnyRole("USER")
			.antMatchers("/admin").hasAnyRole("ADMIN")
			.and().formLogin().loginPage("/login")
				.successHandler(successHandler)
			.permitAll()
			.and().logout();
	}
}	


Step 4 – How UI looks

Admin Login redirects to admin dash board.



Related Articles

Leave a Reply

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