Skip to content

Spring Boot Security is a powerful framework for securing web applications. However, upgrading to the latest versions (Spring Boot 3+ and Spring Security 6.1+) introduces breaking changes, deprecations, and new patterns that require refactoring.

In this guide, we will:
✅ Debug common Spring Security upgrade issues
✅ Upgrade to the latest Spring Boot & Security versions
✅ Implement state-of-the-art best practices


🔍 Common Debugging Issues After Upgrading Spring Security

Upgrading from Spring Boot 2.x → 3.x and Spring Security 5 → 6+ often results in errors like:

  1. Deprecated Methods
    The method cors() from the type HttpSecurity has been deprecated since version 6.1 and marked for removal
    

    ✅ Fix: Use the new Lambda DSL syntax.

  2. Functional Interface Errors
    The target type of this expression must be a functional interface
    

    ✅ Fix: Use the correct method references in security configurations.

  3. Missing Beans (AuthenticationManager & SecurityFilterChain)
    Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager'
    

    ✅ Fix: Explicitly define AuthenticationManager and SecurityFilterChain.

  4. CORS Issues (Blocked Requests in Frontend)
    Access to fetch at 'http://localhost:8080/api' from origin 'http://localhost:4200' has been blocked by CORS policy
    

    ✅ Fix: Ensure proper CORS configuration with CorsConfigurationSource.


🛠️ How to Upgrade to Spring Security 6+ in Spring Boot 3+

1️⃣ Update Dependencies

Modify pom.xml (Maven) to use the latest versions:

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- JWT Token Authentication -->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.11.5</version>
    </dependency>

    <!-- Password Encryption -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-crypto</artifactId>
    </dependency>
</dependencies>

👉 Why?

  • Spring Boot 3+ uses Jakarta EE, replacing javax.servlet with jakarta.servlet.
  • Some Spring Security classes have changed.

2️⃣ Convert WebSecurityConfigurerAdapter to SecurityFilterChain

In Spring Security 6+, WebSecurityConfigurerAdapter is removed. Instead, define security as a SecurityFilterChain bean.

❌ Old Approach (Deprecated)

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/public/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

✅ New Approach (Spring Security 6)

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults());

        return http.build();
    }
}

👉 Why?

  • authorizeRequests() → replaced with authorizeHttpRequests().
  • antMatchers() → replaced with requestMatchers().
  • .and() → not required in lambda-based DSL.

3️⃣ Define AuthenticationManager as a Bean

Spring Security 6 no longer auto-configures AuthenticationManager. You must define it manually.

✅ Fixed Approach

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

4️⃣ Implement Proper CORS Configuration

CORS issues are common in frontend-backend integrations (e.g., Angular, React).

✅ Best Practice: Using CorsConfigurationSource

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(List.of("http://localhost:4200")); // Replace with frontend origin
    configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

5️⃣ Implement JWT-Based Authentication (Modern Approach)

Instead of storing sessions, use JWT (JSON Web Token) authentication.

Generate JWT Token

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

@Service
public class JwtUtil {

    private static final String SECRET_KEY = "your-secret-key";

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }
}

Validate JWT Token

public boolean validateToken(String token) {
    try {
        Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
        return true;
    } catch (Exception e) {
        return false;
    }
}

👉 Why?

  • JWT eliminates the need for server-side session management.
  • Stateless authentication is faster and more scalable.

🔥 Best Practices for Spring Boot Security

  1. ✅ Use SecurityFilterChain instead of WebSecurityConfigurerAdapter.
  2. ✅ Disable CSRF only when using JWT authentication.
  3. ✅ Use requestMatchers() instead of antMatchers().
  4. ✅ Always encrypt passwords with BCryptPasswordEncoder.
  5. ✅ Use JWT instead of traditional sessions.
  6. ✅ Ensure CORS is properly configured for frontend-backend integration.
  7. ✅ Store sensitive config values (secrets, API keys) in environment variables.
  8. ✅ Keep dependencies up to date to avoid security vulnerabilities.

🎯 Final Thoughts

Upgrading to Spring Boot 3+ and Spring Security 6+ brings performance improvements, better security, and modern programming patterns. By migrating from WebSecurityConfigurerAdapter to SecurityFilterChain, fixing CORS, and implementing JWT authentication, you ensure your application is secure, scalable, and up-to-date.


✅ Need Help?
Drop your questions below! 🚀

10 thoughts on “🚀 Debugging, Upgrading & Best Practices in Spring Boot Security (2025 Edition)”

  1. Heya i’m for the primary time here. I found this board and I to
    find It truly helpful & it helped me out a lot.

    I’m hoping to offer one thing back and help others such as you aided me.

  2. Hi, I do believe this is an excellent website. I stumbledupon it
    😉 I may come back once again since i have book marked it.
    Money and freedom is the best way to change, may
    you be rich and continue to help other people.

  3. Heya exceptional blog! Does running a blog like this take a large amount
    of work? I have no knowledge of coding however I had been hoping to start my own blog soon. Anyway, if you have any ideas or techniques for new
    blog owners please share. I know this is off topic nevertheless I simply
    needed to ask. Thanks a lot!

  4. Does your website have a contact page? I’m having trouble locating it
    but, I’d like to shoot you an e-mail. I’ve got some ideas for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it grow
    over time.

Leave a Reply

Discover more from Complex IT Problems = Easy Working Systems.

Subscribe now to keep reading and get access to the full archive.

Continue reading