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.
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.
@RestControllerpublic 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/helloGreetings from Spring Boot!
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"}
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@EnableWebSecuritypublic class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated()).httpBasic(withDefaults());return http.build();}...
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.
@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
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.
@Beanpublic 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@EnableWebSecuritypublic class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated()).httpBasic(withDefaults());return http.build();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic 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:passwordGreetings from Spring Boot!
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.
Quick Links
Legal Stuff