Video in progress

Junior 🌱 Spring

In Spring Security 6, how do you define which URLs are open and which are locked through a SecurityFilterChain bean?

In a @Configuration class you write a @Bean that returns a SecurityFilterChain, and inside authorizeHttpRequests you set rules with requestMatchers. The rules are checked top to bottom, with anyRequest at the very end.

📖 Answer

@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**", "/actuator/health").permitAll()
                .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

The old way, extending WebSecurityConfigurerAdapter, was deprecated in 5.7 and removed completely in 6. Now it's only a bean.

What else changed:

  • authorizeHttpRequests instead of authorizeRequests;
  • requestMatchers instead of antMatchers/mvcMatchers;
  • the lambda DSL instead of .and() chains.

Order matters: if you write .anyRequest().authenticated() first, the later rules never get a turn, and Spring even reports this as an error at startup. Specific rules on top, the general one at the bottom.