Hey guys in this post we will discuss adding spring security to a spring boot application with step by step process.
Table of Contents
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
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
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.security.web.context.request.async.WebAsyncManagerIntegrationFilter@64b70919, org.springframework.security.web.context.SecurityContextPersistenceFilter@24e08d59, org.springframework.security.web.header.HeaderWriterFilter@50a3d0f6, org.springframework.security.web.csrf.CsrfFilter@47547132, org.springframework.security.web.authentication.logout.LogoutFilter@2c6ee758, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@1686f0b4, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@4b54af3d, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@4e31c3ec, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@61e3cf4d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@971e903, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@16ade133, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3157e4c0, org.springframework.security.web.session.SessionManagementFilter@1abc9f14, org.springframework.security.web.access.ExceptionTranslationFilter@2a9bc08f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@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.
Screenshot not vsisble