In spring boot security, the users are allowed to access those features based on the user roles in the Spring boot security application. Spring boot security enables the authentication of web pages based on user roles. In this post, we will see how to create a custom login page, validate the user on the basis of their roles, and redirect to the respective dashboard web pages.
This example is created using Spring Boot + JSP + Tomcat + Spring Security
The custom login page contains two user types with role as user and admin.
Step 1 – Create Pom.xml
Create a spring boot application in Spring Tool Suite. Add spring boot security and spring boot web modules in the application. The spring boot security module enable to configure security in the application.The spring web module allows you to create a web application. The Spring Boot App will run on tomcat by default.
The code below includes a pom.xml file with the necessary dependent modules.
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>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 2 – Add Spring Boot Security configurations
Create a java file for spring boot security configurations. The java class will extends WebSecurityConfigurerAdapter class. In the security configuration class add two user, user and admin with role of USER, ADMIN. All admin related pages are created within /admin url. All the user pages are created within /user url.
src/main/java/com/yawintutor/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("/admin/dashboard").hasAnyRole("ADMIN")
.antMatchers("/user/dashboard").hasAnyRole("USER")
.and().formLogin().loginPage("/login")
.successHandler(successHandler)
.permitAll()
.and().logout();
}
}
There is a successful handler class created by implementing the AuthenticationSuccessHandler interface. This successful handler will redirect the url to the respective user dashboard or admin dashboard pages after a successful login. The success handler checks the role of the logged in user and decides to redirect the dashboard page.
src/main/java/com/yawintutor/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) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
redirectUrl = "/user/dashboard";
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
redirectUrl = "/admin/dashboard";
break;
}
}
if (redirectUrl == null) {
throw new IllegalStateException();
}
new DefaultRedirectStrategy().sendRedirect(request, response, redirectUrl);
}
}
Step 3 – Add Controller class
The controller class is created to manage all the jsp files to map the url. The controller class renders url-based jsp files invoked by the spring boot security configuration class. The security configuration must determine which class to invoke on the basis of the authentication.
src/main/java/com/yawintutor/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("/")
public ModelAndView defaultHome() {
return new ModelAndView("login");
}
@RequestMapping("/home")
public ModelAndView home() {
return new ModelAndView("home");
}
@RequestMapping("/login")
public ModelAndView login() {
return new ModelAndView("login");
}
@RequestMapping("/user/dashboard")
public ModelAndView userDashboard() {
return new ModelAndView("user/dashboard");
}
@RequestMapping("/admin/dashboard")
public ModelAndView admindashboard() {
return new ModelAndView("admin/dashboard");
}
}
Step 4 – Add application.properties
In the application.properties, add the jsp related configurations. The jsp file is identified on the basis of the configuration in the program.
src/main/resources/application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
Step 5 – Add jsp files
In the spring boot applications, jsp files are used for rendering the UI pages. Jsp files contain a basic HTML code that demonstrates how to submit a request and make a page.
src/main/webapp/WEB-INF/jsp/login.jsp
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<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>
<sec:csrfInput />
<input type="submit" name="submit"/>
</form>
</center>
src/main/webapp/WEB-INF/jsp/home.jsp
<center>
<h1>Welcome to Spring Boot Simple Security Example</h1>
<a href="login">login</a>
</center>
src/main/webapp/WEB-INF/jsp/user/dashboard.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/admin/dashboard.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 6 – Test application
Run the spring boot security application after the jsp files have been added. The spring boot application will start the tomcat and run on port 8080. Invoke http:/localhost:8080/home url from one of your browser windows. The default url will point to the file home.jsp. Click on the login link to redirect the default url to the login.jsp file as the security module is configured.
Username : user
Password : password
Username : admin
Password : password
After the successful login, depending on the name of the user entered, the spring boot security role is identified. Depending on the role, the user is redirected to either /user/dashboard.jsp or /admin/dashboard.jsp file.