SecurityFilterChain defines how Spring Security handles HTTP authentication and endpoint authorization. Define it as a bean when the defaults do not match the application. section 2.3.2
Configure the chain through HttpSecurity:
- Call httpBasic(Customizer.withDefaults()) to enable HTTP Basic authentication. section 2.3.2
- Call authorizeHttpRequests() to define endpoint authorization, such as anyRequest().authenticated() or anyRequest().permitAll(). section 2.3.2
- Register a UserDetailsService locally with userDetailsService(), or provide it separately as a Spring bean. section 2.3.3
Protect every endpoint
A minimal configuration enables HTTP Basic authentication and requires authentication for every request. Replace authenticated() with permitAll() when endpoints should accept requests without credentials.
Listing 2.9 Setting UserDetailsService with the SecurityFilterChain bean
@Configuration
public class ProjectConfig {
@Bean
public SecurityFilterChain configure(HttpSecurity http)
throws Exception {
http.httpBasic(Customizer.withDefaults());
http.authorizeHttpRequests(
c -> c.anyRequest().authenticated()
);
var user = User.withUsername("john") #1
.password("12345")
.authorities("read")
.build();
var userDetailsService = #2
new InMemoryUserDetailsManager(user);
http.userDetailsService(userDetailsService); #3
return http.build();
}
// Omitted code
}
Inspect a complete chain that creates an in-memory user, registers its UserDetailsService, and returns the built configuration. section 2.3.3
