Introduction

In this quick tutorial, we'll show how to set up basic authentication in Spring Boot project using Spring Security. Spring Security offers a lot of security methods and this one is the simplest to configure -when you add Spring Security to your classpath, Basic authentication is enabled by default. The only thing we should do is configure the username and password for our default user.

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:

How to set up basic authentication in Spring Boot

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.