Securing REST APIs with Basic Authentication in Spring Boot

Basic Authentication is a simple and stateless authentication mechanism built into the HTTP protocol. It’s easy to implement and useful for:

  • Securing internal APIs
  • Prototyping or quick services
  • Environments where TLS/SSL is enforced (important for securing credentials)

Lets learn how Securing REST APIs with Basic Authentication in Spring Boot can be done.

Securing REST APIs with Basic Authentication in Spring Boot

๐Ÿ“ฆ Project Setup

Maven Dependencies

In your pom.xml, include:

๐Ÿงฉ Project Structure

๐Ÿ” Step 1: Create SecurityConfig for Basic Authentication

๐ŸŒ Step 2: Create a REST Controller

๐Ÿš€ Step 3: Main Spring Boot Application

๐Ÿงช Testing the Endpoints

1. Accessing the public endpoint

๐ŸŸข Output: "This is a public endpoint."

2. Accessing a protected endpoint without credentials

๐Ÿ”ด Output: HTTP/1.1 401 Unauthorized

3. Accessing with Basic Auth

๐ŸŸข Output: "Welcome, authenticated USER."

๐ŸŸข Output: "Welcome, authenticated ADMIN."

โš ๏ธ Important Notes

  • Always use HTTPS with Basic Auth to avoid sending credentials in clear text.
  • Avoid Basic Auth in production unless used with secure environments or in internal microservices behind a gateway.
  • Prefer OAuth2/JWT for public APIs.

๐Ÿ›  Best Practices

  • Use BCryptPasswordEncoder for encoding passwords.
  • Separate roles clearly in SecurityConfig.
  • Add rate-limiting and logging for security-sensitive endpoints.
  • Keep credentials in secure secrets manager, not in plain code or config.

๐Ÿ“š References

๐Ÿ Conclusion

Securing REST APIs with Basic Authentication in Spring Boot is straightforward using Spring Security. With the new Spring Boot 3 and Spring Security 6, configuration is more streamlined using Java configuration with SecurityFilterChain.

Use this setup for quick authentication and secure your internal APIs effectively using Spring’s robust security model.