Horje
Spring Security - Upgrading the Deprecated WebSecurityConfigurerAdapter

Spring Security WebSecurityConfigurerAdapter has been the cornerstone for configuring security in the Spring Boot applications for many years. However, starting from Spring Security 5.4, this class has been deprecated in favor of the more component-based approach using SpringFilterChain and the other configuration classes. In this article, we will learn the existing Spring Security configuration from WebSecurityConfigurerAdapter to the new recommended approach.

Prerequisites:

  • Good understanding of the Spring Boot and Spring Security.
  • JDK and IntelliJ Idea should be set up in your local system.
  • Maven for building dependency management of the project.

Deprecation

The WebSecurityConfigurerAdapter is used to provide the convenient base class to create the WebSecurityConfigurer instance. However, it had limitations in terms of flexibility and clarity. The new approach can leverage the Java configuration’s power by allowing more fine-grained control over the security settings through the SecurityFilterChain bean.

New Approach Overview

This approach involves defining the one or more SecurityFilterChain beans which provides the more flexibility and modularity. Additionally, the configuration is more aligned with the Spring Boot overall component based design of the Spring Boot application.

Upgrading the Deprecated WebSecurityConfigurerAdapter in Spring Security

Below is the step by step implementation to upgrade the deprecated WebSecurityConfigurerAdapter.

Step 1: Remove the WebSecurityConfigurerAdapter Class

In the existing Spring Boot Project, we can locate the class that extends the WebSecurityConfigurerAdapter. It looks like the below code.

Java
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Configuration class for Spring Security.
 * This class extends WebSecurityConfigurerAdapter to provide custom security configurations.
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * Configures the security settings for the application.
     *
     * @param http the HttpSecurity object to configure.
     * @throws Exception if an error occurs during configuration.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // Configure authorization rules
            .authorizeRequests()
                // Allow access to any URL under /public/ without authentication
                .antMatchers("/public/**").permitAll()
                // Require authentication for any other request
                .anyRequest().authenticated()
            .and()
            // Configure form-based login
            .formLogin()
                // Specify the custom login page URL
                .loginPage("/login")
                // Allow everyone to access the login page
                .permitAll()
            .and()
            // Configure logout functionality
            .logout()
                // Allow everyone to access the logout functionality
                .permitAll();
    }
}


Step 2: Define the SecurityFilterChain Bean

Now replace the above configuration with the SecurityFilterChain bean. This can be done in the configuration class as follows:

Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Configuration class for Spring Security.
 * This class defines the SecurityFilterChain bean to provide custom security configurations.
 */
@Configuration
public class SecurityConfig {

    /**
     * Defines the security filter chain.
     *
     * @param http the HttpSecurity object to configure.
     * @return the SecurityFilterChain bean.
     * @throws Exception if an error occurs during configuration.
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // Configure authorization rules
            .authorizeRequests()
                // Allow access to any URL under /public/ without authentication
                .antMatchers("/public/**").permitAll()
                // Require authentication for any other request
                .anyRequest().authenticated()
            .and()
            // Configure form-based login
            .formLogin()
                // Specify the custom login page URL
                .loginPage("/login")
                // Allow everyone to access the login page
                .permitAll()
            .and()
            // Configure logout functionality
            .logout()
                // Allow everyone to access the logout functionality
                .permitAll();
        
        // Return the configured SecurityFilterChain
        return http.build();
    }
}


Step 3: Adjust the other Security Configurations

If you have other security configurations such as the user details service or password encoding then move them to the appropriate the beans or components.

Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.core.userdetails.User;

/**
 * Configuration class for setting up user details service.
 * This class defines the UserDetailsService bean for in-memory user details management.
 */
@Configuration
public class UserConfig {

    /**
     * Defines an in-memory user details service.
     *
     * @return the UserDetailsService bean.
     */
    @Bean
    public UserDetailsService userDetailsService() {
        // Create an in-memory user details manager
        var userDetailsService = new InMemoryUserDetailsManager();
        
        // Define a user with username 'user', password 'password', and role 'USER'
        var user = User.withUsername("user")
                       .password("{noop}password") // {noop} indicates that no password encoder is used
                       .roles("USER")
                       .build();
        
        // Add the user to the in-memory user details manager
        userDetailsService.createUser(user);
        
        // Return the configured UserDetailsService bean
        return userDetailsService;
    }
}


Step 4: Testing the Configuration

After making these changes then restart the Spring Boot application and test the security configuration. We can ensure that the login page is displayed, public pages are accessible without authentication and protected pages required login of the application.

Conclusion

Upgrading from the WebSecurityConfigurerAdapter to the new SecurityFilterChain based configuration in Spring Security is the straightforward process. It enhances the flexibility and aligns with Spring Boot components based design philosophy. By following these steps, we can smoothly transition to the new approach and take advantages of the latest features in the Spring Security.




Reffered: https://www.geeksforgeeks.org


Advance Java

Related
How to Get Number of Messages in a Topic in Apache Kafka in Java? How to Get Number of Messages in a Topic in Apache Kafka in Java?
Concurrency in Spring Webflux Concurrency in Spring Webflux
Rich Domain Model with Hibernate Rich Domain Model with Hibernate
Spring Boot Without A Web Server Spring Boot Without A Web Server
Monitoring and Logging for Reactive Applications Monitoring and Logging for Reactive Applications

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16