Add Spring Security to Spring Boot Application





Hey guys in this post we will discuss adding spring security to a spring boot application with step by step process.

Introduction


Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

Features


  • Comprehensive and extensible support for both Authentication and Authorization
  • Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc
  • Servlet API integration
  • Optional integration with Spring Web MVC
  • Much more…

Complete example


Let’s create a step-by-step spring boot project and add spring security to the application

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?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.4.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springsecuritybasic</artifactId>
	<version>v1</version>
	<name>springsecuritybasic</name>
	<description>Spring security basics</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>
	</dependencies>

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

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.




Later we will add spring-boot-starter-security dependency, which will help to implement spring security.

Create a Rest controller


Create HomeController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
	
	@GetMapping("/home")
	public String showHomePage () { 
		return "Showing the home page contents";
	}
}

We have created a handler method showHomePage() that are mapped to the URI /home, which will return a static text.

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL –

http://localhost:8080/home
Screenshot-2021-05-05-at-8-16-42-PM
In our application, now anyone can access the URI /home, which will return the static text.

Assume that, now we want to secure our application. If anyone tries to access the URI /home, our application needs to authenticate first, once the authentication is successful then only it shows the content.

Add spring security to the application


Now let’s modify our pom.xml by adding the spring-boot-starter-security dependency.

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

Once we add the dependency to the application, by default all the URIs will be secured meaning spring security provides a login page to authenticate the user.

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL –

http://localhost:8080/home
Screenshot-2021-05-05-at-8-16-16-PM
You can see the above image, it displays a login form to authenticate the user. By default, the username will be “user” and the password will be available in the console.

2021-05-05 20:11:29.002  INFO 6151 --- [           main] i.b.s.SpringsecuritybasicApplication     : Starting SpringsecuritybasicApplication using Java 1.8.0_151 on MacBook-Air.local with PID 6151 (/Users/bushansirgur/Documents/workspace-spring-tool-suite-4-4.9.0.RELEASE/springsecuritybasic/target/classes started by bushansirgur in /Users/bushansirgur/Documents/workspace-spring-tool-suite-4-4.9.0.RELEASE/springsecuritybasic)
2021-05-05 20:11:29.005  INFO 6151 --- [           main] i.b.s.SpringsecuritybasicApplication     : No active profile set, falling back to default profiles: default
2021-05-05 20:11:29.970  INFO 6151 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-05-05 20:11:29.981  INFO 6151 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-05-05 20:11:29.981  INFO 6151 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.45]
2021-05-05 20:11:30.043  INFO 6151 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-05-05 20:11:30.043  INFO 6151 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 972 ms
2021-05-05 20:11:30.249  INFO 6151 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2021-05-05 20:11:30.459  INFO 6151 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: f096be49-76d5-4a82-8581-cf95e7973752

2021-05-05 20:11:30.586  INFO 6151 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.secu[email protected]64b70919, org.spring[email protected]24e08d59, [email protected]0f6, [email protected], org.springframework.security.web.authentication.logout.LogoutF[email protected], org.springframework.s[email protected]1686f0b4, org.springframework.[email protected]4b54af3d, org.springframework.s[email protected]4e31c3ec, org.springfram[email protected]61e3cf4d, org.sp[email protected]971e903, org.springframework.[email protected]16ade133, org.springfram[email protected]3157e4c0, o[email protected]1abc9f14, org[email protected]2a9bc08f, org.springfr[email protected]38eb2c50]
2021-05-05 20:11:30.668  INFO 6151 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-05-05 20:11:30.678  INFO 6151 --- [           main] i.b.s.SpringsecuritybasicApplication     : Started SpringsecuritybasicApplication in 2.099 seconds (JVM running for 2.772)

Once you enter the credentials, now you can see the contents. So by adding a single dependency to the application, spring will automatically secure all our URIs.

That’s it for this article, in the next article we will customize the username and password, instead of using the one provided by the Spring security framework.

If you like this post, do share it with your friends and colleagues.




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

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