java / beginner
Snippet
Configuring Basic HTTP Endpoint Security with SecurityFilterChain
Spring Security uses the SecurityFilterChain bean to control URL access. By defining rules inside authorizeHttpRequests, you can make specific paths public while enforcing authentication on all other incoming requests.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration@EnableWebSecuritypublic class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(auth -> auth.requestMatchers("/public/**").permitAll().anyRequest().authenticated()).httpBasic(Customizer.withDefaults());return http.build();}}
spring
Breakdown
1
@Configuration
Marks the class as a source of bean definitions for the Spring application context.
2
@EnableWebSecurity
Enables Spring Security's web security support and provides the Spring MVC integration.
3
.requestMatchers("/public/**").permitAll()
Allows anonymous access to any URL starting with /public/ without credentials.
4
.anyRequest().authenticated()
Requires all other requests to be made by an authenticated user.
5
.httpBasic(Customizer.withDefaults());
Enables standard HTTP Basic authentication headers.