httpBasic is an HttpSecurity configuration method that enables HTTP Basic authentication for a Spring Security filter chain. Pair it with endpoint authorization rules when requests should require credentials. section 2.3.2
Enable authentication and protect endpoints
Call http.httpBasic(Customizer.withDefaults()), then configure authorizeHttpRequests with anyRequest().authenticated(). The default Customizer applies standard behavior; changing the rule to permitAll() leaves endpoints accessible without credentials. section 2.3.2
Listing 2.7 Using the HttpSecurity parameter to alter the configuration
@Configuration
public class ProjectConfig {
@Bean
SecurityFilterChain configure(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults()); #1
http.authorizeHttpRequests(
c -> c.anyRequest().authenticated() #2
);
return http.build();
}
// Omitted code
}
A compact SecurityFilterChain example connects HTTP Basic authentication with authenticated endpoint access. section 2.3.2
Customize the challenge response
Pass a lambda Customizer to set realmName("OTHER") or install an AuthenticationEntryPoint. The entry point can add response headers and return a 401 status for failed authentication. section 6.3.1
