DEV Community

Andrii Maliuta
Andrii Maliuta

Posted on

Spring Security without the WebSecurityConfigurerAdapter

Since Spring Security 5.7.0-M2 the use of WebSecurityConfigurerAdapter was deprecated (link to GitHub - https://github.com/spring-projects/spring-security/issues/10822) to move to component-based security configuration.

To adhere to the best practices of Spring Security, it is better to use lambda DSL and the method HttpSecurity#**authorizeHttpRequests **to define the authorization rules.

So, instead of :

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
    }

}
Enter fullscreen mode Exit fullscreen mode

it is better to use:

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
        return http.build();
    }

}
Enter fullscreen mode Exit fullscreen mode

More details in official Spring blog - https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter.

Top comments (0)