Implementation
First, we should add Spring security Maven dependency to our pom.xml file:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
Also, we'll create a simple endpoint to test our authentication. For the purpose of simplicity, it will only return a string.
package com.javahowtos.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@GetMapping("/api/basicauthdemo")
public String getSomeResponse() {
return "Hello!";
}
}
Then, we'll configure the username and password in application.yml file:
spring:
security:
user:
name: myUsername
password: somepassword
And that's it. Now, let's try this out using Postman:
If you're using some other tool, be sure that it sends Authorization header follows "Basic Base64EncodedString" rule where Base64EncodedString represents Base64 encoded username:password string.
Conclusion
In this tutorial, we created a simple project and configured a basic authentication for a Spring Boot project. The complete code could be found on GitHub.