HomeAbout MeContact
Spring Boot
Spring Boot Basic Auth
Piotr Szarpak
Piotr Szarpak
December 08, 2023
2 min
Make sure to subscribe to our newsletter and be the first to know the news.

Spring Boot: Basic Authentication

spring boot basic auth Spring Boot provides a lot of autoconfiguration to make our life easier. One of them is Basic Authentication. In this article, I will show you how to use it.

Initial setup

First of all, we need to create a new Spring Boot project. We can do it by using Spring Initializr. Let’s assume we already have a hello controller with a single endpoint.

@RestController
public class HelloController {
@GetMapping("/hello")
public String index() {
return "Greetings from Spring Boot!";
}
}

We can run our application and check if everything works as expected.

$ curl localhost:8080/hello
Greetings from Spring Boot!

Setup Spring Security

Now, we can add Spring Security to our project. We can do it by adding the following dependency to our pom.xml file.

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

This dependency will automatically add Spring Security to our project. As a result, all endpoints will be secured by default. If we try to call our endpoint again, we will get a 401 response.

$ curl localhost:8080/hello
{"timestamp":"2020-04-10T12:00:00.000+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/hello"}

Add Security Configuration

Now, we need to add a security configuration to our project. We can do it by adding an annotation @EnableWebSecurity to our configuration class. Then, we need to create a bean of type SecurityFilterChain. We can do it by using the HttpSecurity builder. Within the builder, we need to configure our security. In this example, we will allow all requests to be authenticated with basic authentication. We can do it by using the authorizeHttpRequests method.

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(
auth -> auth.anyRequest().authenticated()
)
.httpBasic(withDefaults())
;
return http.build();
}
...

Encode password

We need to also provide a password encoder. The password encoder is basically a function that will encode our password. This way our password will not be stored in plain text. We can do it by using the BCryptPasswordEncoder implementation.

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

Add user

Last but not least, we need to add a user to our application that will be authorized to call our endpoint. We can do it by using the UserDetailsService interface. In this example, we will use the InMemoryUserDetailsManager implementation. We can create a user by using the User builder. We need to provide a username and password. The user password is “password”. We need to encode it by using the BCryptPasswordEncoder implementation.

@Bean
public UserDetailsService users() {
UserDetails admin = User.builder()
.username("admin")
.password("$2a$10$3vsR9PKlSE5SezhTZCLIyuVi991RMGKEi2Yx.O5YibdA.fODs8lqy")
.build();
return new InMemoryUserDetailsManager(admin);
}

The full configuration class should look like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(
auth -> auth.anyRequest().authenticated()
)
.httpBasic(withDefaults())
;
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService users() {
UserDetails admin = User.builder()
.username("admin")
.password("password")
.build();
return new InMemoryUserDetailsManager(admin);
}
}

Now, we can call our hello endpoint again. This time we need to provide a username and encoded password.

$ curl localhost:8080/hello -u admin:password
Greetings from Spring Boot!

Summary

In this article, we learned how to use basic authentication in Spring Boot. We can do it by adding the spring-boot-starter-security dependency to our project. Then, we need to add a security configuration. We can do it by using the @EnableWebSecurity annotation. Within the configuration, we need to provide a SecurityFilterChain bean. We can do it by using the HttpSecurity builder. Then, we need to configure our security. In this example, we allowed all requests to be authenticated with basic authentication. We can do it by using the authorizeHttpRequests method. Last but not least, we need to provide a user that will be authorized to call our endpoint. We can do it by using the UserDetailsService interface. In this example, we used the InMemoryUserDetailsManager implementation. We can create a user by using the User builder. We need to provide a username and password.


Tags

Share

Piotr Szarpak

Piotr Szarpak

Java passionate

Sed commodo, est quis maximus fermentum, massa ipsum euismod neque, in varius risus tellus quis lacus. Sed ac bibendum odio.

Expertise

Java > 11
DDD
Spring
Databases

Social Media

githubtwitterwebsite

Related Posts

Spring Security Fundamentals
Spring Security Fundamentals
March 14, 2024
3 min
© 2024, All Rights Reserved.
Powered By

Quick Links

Advertise with usAbout UsContact Us

Social Media