My team is struggling with the migration to Spring Security 6. The WebSecurityConfigurerAdapter is gone, and the new functional configuration style is quite confusing. How do we properly set up a SecurityFilterChain for a JWT-based REST API while ensuring we don't accidentally leave our Actuator endpoints exposed to the public?
3 answers
The shift to the Lambda DSL in Spring Security 6 is designed to improve readability and prevent the "and()" method chaining mess of the past. To secure your API, you must define a @Bean of type SecurityFilterChain. Inside, you use http.authorizeHttpRequests(auth -> auth.requestMatchers("/api/public/**").permitAll().anyRequest().authenticated()). For JWT, you’ll add .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())). Regarding Actuator, you should explicitly secure it by adding a matcher for /actuator/** that requires an 'ADMIN' role. I performed this migration for a client in mid-2023, and the key is to ensure you aren't mixing the old antMatchers with the new requestMatchers, as the bean ordering has changed.
Did you run into any issues with Cross-Origin Resource Sharing (CORS) after the migration, as the configuration for the CorsFilter seems to have changed its priority in the filter chain?
The new DSL is much more "Java-centric" and less like a custom language. It makes it easier to use standard Java logic within your security configuration if needed.
Agreed, Sarah. It’s a lot more intuitive once you get used to the lambda syntax. It also makes it easier to see exactly which filters are being applied to which endpoints.
Joseph, yes! Our frontend started throwing 403 errors on preflight OPTIONS requests immediately after the upgrade. It turns out that in Spring Security 6, you need to define the CorsConfigurationSource as a bean and then explicitly link it in the http.cors() DSL. Once we did that and moved the CORS configuration out of the old Global WebMvc config, the preflight checks started passing again. It was a frustrating afternoon of debugging, but the logs finally pointed us in the right direction.