WebSecurityConfigurerAdapter is deprecated

Since in Spring Security 5.7.0-M2 WebSecurityConfigurerAdapter is deprecated, there is a new way to set up the configuration, I tested in my file.

With WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  

  @Bean
  public UserDetailsService userDetailsService(){
    return new CustomUserDetailsService();
  }

  @Bean
  public BCryptPasswordEncoder bCryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
  }

  @Bean
  public DaoAuthenticationProvider daoAuthenticationProvider(){
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService());
    authProvider.setPasswordEncoder(bCryptPasswordEncoder());
    return authProvider;
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests()
            .antMatchers("show_list").authenticated()
            .anyRequest().permitAll()
            .and()
            .formLogin()
            .usernameParameter("email")
            .defaultSuccessUrl("/show_list")
            .permitAll()
            .and()
            .logout().logoutSuccessUrl("/").permitAll();
  }
}

Without using WebSecurityConfigurerAdapter:

@Configuration
public class WebSecurityConfig {

  @Bean
  public UserDetailsService userDetailsService() {
    return new CustomUserDetailsService();
  }


  @Bean
  public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http.authorizeHttpRequests()
            .antMatchers("show_list").authenticated()
            .anyRequest().permitAll()
            .and()
            .formLogin()
            .usernameParameter("email")
            .defaultSuccessUrl("/show_list")
            .permitAll()
            .and()
            .logout().logoutSuccessUrl("/").permitAll();

    http.headers().frameOptions().sameOrigin();

    return http.build();
  }
}

Reference:

Spring Security without the WebSecurityConfigurerAdapter

Leave a Comment

Your email address will not be published. Required fields are marked *