0
0
SpringbootHow-ToBeginner · 4 min read

How to Use Basic Authentication in Spring Framework

To use Basic Authentication in Spring, configure Spring Security by adding an HttpSecurity rule that enables httpBasic(). Then define users and passwords in memory or via a user service. This setup prompts clients to send credentials in the HTTP header for access control.
📐

Syntax

Basic authentication in Spring Security is enabled by configuring the HttpSecurity object in a security configuration class. The key method is http.httpBasic(), which tells Spring to expect HTTP Basic credentials.

  • http.authorizeHttpRequests(): Defines which requests need authentication.
  • anyRequest().authenticated(): Requires authentication for all requests.
  • httpBasic(): Enables Basic Authentication.
  • InMemoryUserDetailsManager(): Creates users with passwords in memory for testing.
java
import org.springframework.context.annotation.Bean;
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;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .anyRequest().authenticated()
        )
        .httpBasic();
    return http.build();
}

@Bean
public InMemoryUserDetailsManager userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder()
        .username("user")
        .password("password")
        .roles("USER")
        .build();
    return new InMemoryUserDetailsManager(user);
}
💻

Example

This example shows a minimal Spring Boot application with basic authentication enabled. It protects all endpoints and requires the user to authenticate with username user and password password.

java
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class BasicAuthApplication {

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

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .httpBasic();
        return http.build();
    }

    @Bean
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();
        return new InMemoryUserDetailsManager(user);
    }

    @RestController
    class HelloController {
        @GetMapping("/")
        public String hello() {
            return "Hello, authenticated user!";
        }
    }
}
Output
When accessing http://localhost:8080/, the browser prompts for username and password. After entering 'user' and 'password', the page shows: Hello, authenticated user!
⚠️

Common Pitfalls

Common mistakes when using basic authentication in Spring include:

  • Not enabling httpBasic() in the security config, so authentication never triggers.
  • Forgetting to define users, resulting in no valid credentials.
  • Using plain text passwords without encoding in production (use password encoders).
  • Not securing endpoints properly, allowing anonymous access.

Always test with a client like a browser or curl to confirm authentication works.

java
/* Wrong: Missing httpBasic() disables basic auth prompt */
http
    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());

/* Right: Enables basic auth prompt */
http
    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
    .httpBasic();
📊

Quick Reference

Summary tips for basic authentication in Spring:

  • Use http.httpBasic() to enable basic auth.
  • Define users with passwords using InMemoryUserDetailsManager or a custom user service.
  • Protect endpoints with authorizeHttpRequests().
  • Use password encoders for security in real apps.
  • Test with browsers or tools like curl.

Key Takeaways

Enable basic authentication in Spring by calling httpBasic() in your security configuration.
Define users and passwords using InMemoryUserDetailsManager or a custom user service.
Protect your endpoints by requiring authentication with authorizeHttpRequests().
Always use password encoding for production security.
Test authentication using a browser or curl to verify credentials are required.