Spring Boot 3 and Spring Security 6 represent a fundamental architectural shift for enterprise Java applications. The most disruptive change in this release cycle is the complete removal of the WebSecurityConfigurerAdapter. Applications built on Spring Boot 2.x relied heavily on extending this abstract class to configure HTTP security, authentication managers, and static resource handling. With Spring Security 6, that inheritance-based approach is entirely deprecated and removed. Security configurations must now be implemented using a component-based model powered by lambda-style DSLs and Spring Bean definitions.
This guide walks through the exact architectural patterns required to migrate a legacy Spring Boot 2.x security configuration to Spring Boot 3. Along the way, you will learn how to handle method security, define custom filter chains, manage authentication providers, and prevent common runtime regressions.
The Architectural Shift: From Inheritance to Components
Under the legacy paradigm, developers created custom configuration classes that extended WebSecurityConfigurerAdapter. This tightly coupled security logic to Spring's internal configuration lifecycle and forced method overrides for tasks like ignoring requests or defining password encoders.
Spring Security 6 discards this pattern in favor of functional, component-based configuration. Instead of overriding methods on an abstract class, you declare a SecurityFilterChain bean within a class annotated with @Configuration and @EnableWebSecurity. This decouples the security rules from the configuration container and aligns cleanly with modern Java design principles.
Before beginning the migration, ensure your runtime baseline matches Spring Boot 3 requirements. You will need Java 17 or Java 21. If you are exploring high-throughput concurrency models, you can also optimize your server runtimes by referencing our Spring Boot 3 and Java 21 Virtual Threads Performance Guide.
Step 1: Updating Dependencies and Java Versions
Start by updating your pom.xml or build.gradle file to target Spring Boot 3.x and Spring Security 6.x. Ensure your compiler settings point explicitly to Java 17 or Java 21.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>17</java.version>
</properties>
Step 2: Migrating WebSecurityConfigurerAdapter
Consider a typical legacy Spring Boot 2 configuration using WebSecurityConfigurerAdapter:
// LEGACY: Do not use in Spring Boot 3
@Configuration
@EnableWebSecurity
public class LegacySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
}
}
To migrate this code to Spring Security 6, remove the class extension, inject HttpSecurity via method parameters if needed, and register the SecurityFilterChain as a managed Spring bean. Notice also that matchers use requestMatchers() instead of antMatchers(), and configurations use lambda expressions instead of method chaining.
// MODERN: Spring Boot 3 / Spring Security 6
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form.permitAll());
return http.build();
}
}
Comparison: Spring Security 5 vs. Spring Security 6
The following table outlines the structural differences between the legacy adapter pattern and the modern component model.
| Feature | Spring Security 5 (Legacy) | Spring Security 6 (Modern) |
|---|---|---|
| Configuration Style | Inheritance (extends WebSecurityConfigurerAdapter) |
Component-based (SecurityFilterChain Bean) |
| HTTP Matchers | antMatchers() / mvcMatchers() |
requestMatchers() (Strict Pattern Matching) |
| CSRF / CORS | Chaining (.csrf().disable()) |
Lambdas (.csrf(csrf -> csrf.disable())) |
| Authentication Manager | Exposed via authenticationManagerBean() |
Exposed via AuthenticationConfiguration |
| Password Encoding | NoOpPasswordEncoder (Insecure defaults) | Explicit Bean Declaration Required |
Step 3: Configuring AuthenticationManager and Password Encoders
In older applications, exposing the AuthenticationManager required overriding a protected method on the adapter. In Spring Security 6, you obtain the AuthenticationManager from the AuthenticationConfiguration bean provided by the framework context.
Furthermore, Spring Security 6 does not supply a default PasswordEncoder. You must explicitly define a bean for hashing credentials securely, such as BCryptPasswordEncoder.
@Configuration
@EnableWebSecurity
public class AuthConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public UserDetailsService userDetailsService(PasswordEncoder encoder) {
UserDetails admin = User.builder()
.username("admin")
.password(encoder.encode("secretpassword"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
}
Step 4: Migrating Method-Level Security
If your application relies on annotations like @PreAuthorize or @Secured on service or controller layers, global method security requires explicit activation via @EnableMethodSecurity.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class MethodSecurityConfig {
// SecurityFilterChain definitions go here
}
Once enabled, you can secure individual components cleanly:
@Service
public class ReportService {
@PreAuthorize("hasRole('ADMIN')")
public List<String> generateSecureReport() {
return List.of("Sensitive Data 1", "Sensitive Data 2");
}
}
When writing automated tests for these secured components, ensure your test slices match the new security configuration context. For testing fundamentals, refer to Introduction to JUnit 5 Testing in Spring Boot.
Real-World Edge Cases and Mitigations
Migrating enterprise codebases frequently exposes edge cases that standard tutorials overlook. Below are three common scenarios encountered during upgrades to Spring Security 6.
1. Handling Static Resources and H2 Consoles
In Spring Security 5, ignoring static resources or development tools like the H2 database console was often done via web.ignoring().antMatchers(...). In Spring Security 6, the recommended approach is to define separate filter chains or permit requests explicitly within the primary filter chain using requestMatchers(PathRequest.toH2Console()).
@Bean
@Order(1)
public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatcher(PathRequest.toH2Console())
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
.csrf(csrf -> csrf.disable())
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()));
return http.build();
}
2. Custom JWT Filters and Stateless Sessions
If your application uses JSON Web Tokens (JWT) for stateless REST APIs, configuring session management has changed. The fluent API now relies on lambdas and SessionCreationPolicy.STATELESS.
@Bean
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
http
.securityMatcher("/api/**")
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
3. CORS Configuration Integration
Cross-Origin Resource Sharing (CORS) rules must be explicitly tied into the security filter chain. If you previously configured CORS globally, ensure the security configuration acknowledges it via http.cors(Customizer.withDefaults()) and that a proper CorsConfigurationSource bean is present.
@Bean
public SecurityFilterChain corsSecurityFilterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("https://trusted-frontend.com"));
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
configuration.setAllowedHeaders(List.of("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
If you plan to containerize your newly migrated application alongside a MySQL database for production deployments, check out our guide on Dockerizing a Spring Boot Application with MySQL.
Troubleshooting Common Migration Errors
When running your application for the first time after upgrading, you may encounter specific runtime errors. Here is how to resolve them:
- Bean Currently in Creation Exception: This often happens due to circular dependencies when injecting the
AuthenticationManagerinto custom filters. Ensure you obtain the manager viaAuthenticationConfigurationrather than wiring user details services directly into filter constructors circularly. - 403 Forbidden on All Endpoints: If every request returns a 403 status code, verify that you replaced
antMatchers()withrequestMatchers(). Spring Security 6 matcher resolution is stricter regarding context paths and servlet mappings. - Missing PasswordEncoder Bean: If startup fails with an
IllegalArgumentExceptionstating there is no PasswordEncoder mapped for id "null", ensure you have explicitly defined aPasswordEncoderbean in your configuration classes.
Summary
Migrating from WebSecurityConfigurerAdapter to Spring Security 6 in Spring Boot 3 requires abandoning class inheritance in favor of modular, component-based bean definitions. Key takeaways from this migration include:
- Replacing deprecated adapter classes with explicit
SecurityFilterChainbean definitions. - Adopting lambda-based DSL syntax for configuring HTTP security rules, CSRF protection, and session policies.
- Replacing
antMatchers()with strictrequestMatchers()calls across all security configurations. - Enabling method-level security explicitly using
@EnableMethodSecurity. - Registering explicit encoder and authentication manager beans to satisfy Spring Security 6 requirements.
Comments
Post a Comment