Implementing Basic Authentication with Spring Security

Implementing Basic Authentication With Spring Security

In this article I’ll show you how to implement Basic Authentication with Spring Security, in particular we will see the configuration and customization by creating a simple application.

We’ll cover only the in-memory authentication in this article. If you’re looking for database authentication check out this article.

Basic Authentication

Basic Authentication is a simple authentication integrated in the HTTP protocol. The client sends HTTP requests with the Authorization header containing the word Basic followed by a space and a base64 encoded string username:password.

Dependencies

Everything about security in Spring is implemented in the Spring Security project, so we’re going to use the spring-boot-starter-security dependency.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.1.0</version>
</parent>

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

Spring Security Configuration

To enable authentication and authorization support in the Spring API you need to do some simple configurations.

We need to configure the HttpSecurity class used to configure the security of HTTP requests, then we create an instance of the InMemoryUserDetailsManager class to authenticate the user and we encode the password with BCryptPasswordEncoder.

@Configuration
public class SecurityConfig {

	@Bean
	public InMemoryUserDetailsManager userDetailsService() {
		UserDetails user = User.withUsername("user").password(passwordEncoder().encode("userPassword"))
				.roles("SIMPLE_USER").build();
		return new InMemoryUserDetailsManager(user);
	}

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated()).httpBasic(Customizer.withDefaults());
		return http.build();
	}

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

}

The AuthenticationManager is not the focus of this tutorial, so we use in-memory authentication rather than using a database.

Controller

Now let’s create a simple controller to test authentication.

@RestController
public class MessageController {

	@GetMapping("/messages")
	public Map<String, String> getMessage() {
		return Map.of("message", "Ok");
	}

}

Application Testing

At this point it’s time to test if our application works correctly. We’ll use Postman to test, but curl or other software that can make http calls is also fine.

Let’s try calling the application’s /messages api without providing credentials.

Implementing Basic Authentication with Spring Security

As expected we get a 401 (unauthorized) error because we didn’t provide the credentials.

Now, let’s try this time by entering the credentials.

Now, as a response we get a 200 OK so everything works fine.

Conclusion

In this tutorial, we secured an application with Spring Security and Basic Authentication. We discussed the configuration and customization, finally we tried the application through Postman.

We have also seen how it is not difficult to implement Basic Authentication with Spring Security, because Spring framework provides us with all the necessary tools.

The project is available on GitHub.

Lorenzo Miscoli

Software Developer specialized in creating and designing web applications. I have always loved technology and dreamed of working in the IT world, to make full use of my creativity and realize my ideas.
Scroll to Top