0
0
Spring Bootframework~5 mins

HTTP Basic authentication in Spring Boot

Choose your learning style9 modes available
Introduction

HTTP Basic authentication helps protect your web app by asking users for a username and password before they can access certain pages.

You want a simple way to secure admin pages in your Spring Boot app.
You need to quickly protect an API endpoint without complex login forms.
You want to test authentication in development without building a full login system.
Syntax
Spring Boot
http
  .authorizeHttpRequests(auth -> auth
    .anyRequest().authenticated()
  )
  .httpBasic();
This code goes inside your Spring Security configuration class.
It tells Spring Boot to require authentication for all requests and use HTTP Basic.
Examples
This example secures only URLs under /admin/, letting others be public.
Spring Boot
http
  .authorizeHttpRequests(auth -> auth
    .requestMatchers("/admin/**").authenticated()
    .anyRequest().permitAll()
  )
  .httpBasic();
Complete method to enable HTTP Basic authentication for all requests.
Spring Boot
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  return http
    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
    .httpBasic()
    .and()
    .build();
}
Sample Program

This Spring Boot app requires HTTP Basic authentication for all pages. When you visit any URL, the browser will ask for username and password.

Spring Boot
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@SpringBootApplication
public class DemoApplication {

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

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    return http
      .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
      .httpBasic()
      .and()
      .build();
  }
}
OutputSuccess
Important Notes

HTTP Basic sends credentials encoded but not encrypted. Use it only over HTTPS to keep passwords safe.

Spring Boot by default creates a user with a generated password printed in the console when the app starts.

Summary

HTTP Basic authentication is a simple way to protect web resources with username and password.

Spring Boot makes it easy to enable with just a few lines in your security config.

Always use HTTPS with HTTP Basic to keep credentials secure.