Skip to content

๐Ÿš€ Debugging, Upgrading & Best Practices in Spring Boot Security (2025 Edition)

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 Sowft | Transforming Ideas into Digital Success

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

Continue reading