Spring Security Basic Authentication to Secure REST APIs
In this example, we will learn how to use Spring Security Basic Authentication to secure REST APIs in Spring Boot.
Basic Authentication
• This is the most basic option to secure the REST APIs.
• This uses an HTTP header in order to provide the username and password when making a request to a server.
• This uses a Base 64 encoded username and password in the header.
Table of content
1. Keep Eclipse IDE ready(STS integrated)
2. Create a Spring Boot Starter Project
3. Maven Dependency
4. Define configuration in the application.properties file
5. Create a Spring Security Configuration class
6. Create a Controller
7. Run the app
8. Conclusion
1. Keep Eclipse IDE ready(STS integrated)
Refer to this article How to Create Spring Project in IDE to create Spring Boot Project in Eclipse IDE.
2. Create a Spring Boot Starter Project
Add the following dependencies:
• Spring Web
• Spring Security
3. Maven 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.7.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.springjava</groupId>
<artifactId>Spring_Security_Basic_Authentication_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring_Security_Basic_Authentication_Example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>16</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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>
4. Define configuration in the application.properties file
server.port=8899
5. Create a Spring Security Configuration class
SecurityConfig.java
package com.springjava.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public static PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeHttpRequests((authorize) -> {
authorize.anyRequest().authenticated();
}).httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails admin = User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
}
→ In the SecurityConfig class, we configured Spring Security to use basic in-memory authentication.
→ PasswordEncoder is a Service interface for encoding passwords.
→ BCryptPasswordEncoder is a class. This implementation of PasswordEncoder uses the BCrypt strong hashing function.
→Servlet Filter known as the Spring SecurityFilterChain, which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the login form, and so on) within our application.
→ HttpSecurity class allows configuring web-based security for particular HTTP requests.
→ UserDetailsService interface is used to get user-related data.
6. Create a Controller
MessageController.java
package com.springjava.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MessageController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Security";
}
}
7. Run the app
Right-click on SpringBootApplication class(SpringSecurityBasicAuthenticationExampleApplication) then click on Run as Java Application.
Testing REST API using Postman
Get Type: http://localhost:8899/hello
Click on the Authorization menu then select Basic Auth after that enter username and password.
If we don’t pass the username and password then we will get a 401 status response from this API.
8. Conclusion
In this example, we learnt how to secure Rest API using Spring Security Basic Authentication in Spring Boot Application.
Leave your thought here
Your email address will not be published. Required fields are marked *