0 day streak
java / beginner
Snippet

Configuring Basic HTTP Authorization Rules in Spring Security

Spring Security uses SecurityFilterChain to evaluate incoming requests and enforce access rules according to URL path patterns and user roles.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
spring
Breakdown
1
.requestMatchers("/public/**").permitAll()
Allows all users, including unauthenticated guests, to access endpoints under /public/.
2
.requestMatchers("/admin/**").hasRole("ADMIN")
Restricts all paths starting with /admin/ strictly to users granted the ADMIN role.
3
.anyRequest().authenticated()
Requires every remaining endpoint to have an authenticated session.