In Spring boot security, we’ll see how to create a simple custom login page using spring boot security example step by step. This post allows you to create users with a single user role. Users are allowed to access all pages by default when they are authenticated using spring boot security login page. The Spring boot security authenticates the user before calling the login controller. The spring boot security dependency module is “spring-boot-starter-security”.
This example is created using Spring Boot + JSP + Tomcat + Spring Boot Security + User Roles
Step 1 – Create project
Create a simple spring boot project in the Spring Tool Suite. Add the “spring-boot-starter-web” and “spring-boot-starter-security” dependence while creating a project. Manually add “tomcat-embed-jasper” and “jstl” dependence. After the project is created, the pom.xml file will be shown as below.
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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringBootSecuritySimpleApplication.java
package com.yawintutor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootSecuritySimpleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecuritySimpleApplication.class, args);
}
}
Step 2 – Add Controller Class
Create a controller class for the spring boot security application. The controller class will receive the http request from the browser, process the request and send the response back to the browser.
Create a class of controllers as shown below. Add two methods, the default method that shows a page after the user has been authenticated. The second page of the page is a login page. If the user is not logged in, the request will be forwarded to this login page.
TestController.java
package com.yawintutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping
public class TestController {
@RequestMapping("/")
public ModelAndView defaultHome() {
return new ModelAndView("home");
}
@RequestMapping("/login")
public ModelAndView login() {
return new ModelAndView("login");
}
}
Step 3 – Add Jsp files
In the controller class, two jsp files are configured, i.e. home and login. Create two jsp files to the request server. The home.jsp file contains a log-in success message. If the user logs in successfully, this page will be displayed.
The second page is a login page. If the user does not have a valid session, the user will be prompted to this login page first. User must enter a valid username and password. Upon validation of user details, the user is allowed to log in via the spring boot security module.
application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
home.jsp
<center>
<h1>Welcome to Spring Boot Simple Security Example</h1>
<a href="/logout">logout</a>
</center>
login.jsp
<center>
<h1>Welcome to Spring Boot Security</h1>
<h2>Login Page</h2>
<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>
Step 4 – Spring Boot Security Configurations
Create a Java class to configure security settings. The spring boot security configuration class must be extended to the WebSecurityConfigurerAdapter class. This class allows the user details to be configured. This example uses the memory database to configure user details. User authorization and authentication details are provided in this custom class. The user will be authenticated on the basis of this security configuration.
SpringBootSecurityConfiguration.java
package com.yawintutor;
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;
@Configuration
public class SpringBootSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/**").hasAnyRole("USER")
.and()
.formLogin().loginPage("/login").permitAll();
}
}
Step 5 – Run the application
Run the spring boot security application after the configuration class has been added. The spring boot application will start the tomcat and run on port 8080. Call the default http:/localhost:8080 url from one of the browser windows. The default url will point to the home.jsp file. The default url is redirected to login.jsp file as the security module is configured.
Username : user
Password : password
After entering the valid username and password, the user can log in to the spring boot application. User can click the log out link to sign off the application.
Click the logout button, returns back to login page.