Basic Authentication with Spring Boot Security: A Complete Guide with Full Example

2 min read

Basic Authentication with Spring Boot Security: A Complete Guide with Full Example

Spring Security is a powerful and highly customizable authentication and access-control framework. One of the simplest ways to secure a Spring Boot application is to use HTTP Basic Authentication, where the client sends a username and password with each request.

This article walks you through a step-by-step example of how to implement basic authentication using Spring Boot Security.


What is Basic Authentication?

HTTP Basic Authentication is a simple mechanism where the client sends the username and password in the Authorization header with each request:

Authorization: Basic base64(username:password)

Basic authentication should always be used over HTTPS to prevent credential leakage.


Project Setup

1. Dependencies (pom.xml)

Make sure you include Spring Boot Starter Web and Security:

<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>

Folder Structure

src
 └── main
     ├── java
     │    └── com.example.demo
     │         ├── DemoApplication.java
     │         ├── controller/HelloController.java
     │         └── config/SecurityConfig.java
     └── resources
          └── application.properties

Spring Security Configuration

Create a custom security configuration class:

SecurityConfig.java

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User
            .withUsername("user")
            .password("{noop}password") // {noop} means no password encoder
            .roles("USER")
            .build();

        return new InMemoryUserDetailsManager(user);
    }

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

@Bean returns an in-memory user with the username user and password password.


Create a REST Controller

HelloController.java

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, authenticated user!";
    }
}

application.properties

You can leave it empty or add server customizations:

server.port=8080

Run the Application

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Test the Endpoint

Now test the endpoint using curl or Postman:

Using Curl:

curl -u user:password http://localhost:8080/hello

You should get:

Hello, authenticated user!

Without Authentication:

curl http://localhost:8080/hello

You’ll receive a 401 Unauthorized response.


Security In Action

Browser Test


Common Use Cases

  • Internal admin tools
  • Low-security APIs
  • Quick prototyping

Production Considerations

  • Always use HTTPS with Basic Auth.
  • Use password encoders like BCryptPasswordEncoder for real apps.
  • For more complex setups, consider JWT or OAuth2.

Conclusion

Basic Authentication is a great way to get started quickly with Spring Security. Though limited, it’s a solid choice for internal tools and prototyping. For production, layer it with HTTPS and move to more secure authentication methods when needed.

🤞 Never miss a story from us, get weekly updates to your inbox!

Leave a Reply

Your email address will not be published. Required fields are marked *