Skip to main content

Spring Boot 3 Security Migration Guide with Spring Security 6

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.

Pick a language, then press Listen.

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

Spring Boot 3 Security Migration Workflow Spring Boot 3 Security Migration Workflow 1 Upgrade Runtime & Build Update to Java 17/21 and Spring Boot 3.x in build configuration. 2 Remove Deprecated Adapter Delete legacy classes extending WebSecurityConfigurerAdapter. 3 Define Security Bean Create a SecurityFilterChain bean using @EnableWebSecurity. 4 Adopt Lambda DSLs Configure HTTP security rules and auth using lambda-style DSLs.
Figure: Spring Boot 3 Security Migration Workflow

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 AuthenticationManager into custom filters. Ensure you obtain the manager via AuthenticationConfiguration rather 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() with requestMatchers(). Spring Security 6 matcher resolution is stricter regarding context paths and servlet mappings.
  • Missing PasswordEncoder Bean: If startup fails with an IllegalArgumentException stating there is no PasswordEncoder mapped for id "null", ensure you have explicitly defined a PasswordEncoder bean 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 SecurityFilterChain bean definitions.
  • Adopting lambda-based DSL syntax for configuring HTTP security rules, CSRF protection, and session policies.
  • Replacing antMatchers() with strict requestMatchers() 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

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...