0 day streak
java / beginner
Snippet

Configuring Basic HTTP Endpoint Protection via SecurityFilterChain

Spring Security controls access to web routes through the SecurityFilterChain bean. In this configuration, endpoints under '/api/public/**' are publicly accessible without credentials, while all other requests require authentication via HTTP Basic Auth. Defining this bean establishes clear boundaries for API authorization.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
spring
Breakdown
1
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http)
Declares the security filter chain bean used by Spring Security to inspect and authorize incoming requests.
2
.requestMatchers("/api/public/**").permitAll()
Allows unauthenticated access to all URL paths matching the '/api/public/**' pattern.
3
.anyRequest().authenticated()
Mandates that any request not explicitly permitted requires valid user authentication.