Home > Enterprise >  using Authentication Provider without using WebSecurityConfigurerAdapter in Spring Security 5.7.0
using Authentication Provider without using WebSecurityConfigurerAdapter in Spring Security 5.7.0

Time:06-30

Now I am trying to implement spring security authentication provider for my spring boot spring security project. So previously we were able to extend WebSecurityConfigurerAdapter in our Security config file to customize the http and HttpSecurity http and AuthenticationManagerBuilder auth by overriding configure.

But now (Spring Security 5.7.0) WebSecurityConfigurerAdapter got deprecated and I am following WebSecurityCustomizer method like the following,

@EnableWebSecurity
@Configuration
public class SecurityConfig{

 @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                .antMatchers("/users/getUser");
    }

}

So Here using WebSecurityCustomizer , how can I use authentication provider functionality in my ReST API ? Can anyone guide me to solve this issue or kindly suggest updated documentation for refer please?

CodePudding user response:

I don't think that the WebSecurityCustomizer is the bean that you want to use in this case. I guess that what you are trying to do is to configure a SecurityFilterChain, like so:

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

Anyways, it is not recommended to disable Spring Security in a certain endpoint, the alternative is to use authorizeHttpRequests.antMatchers("/my-endpoint").permitAll() if you don't want security on that endpoint.

About the AuthenticationProvider and AuthenticationManager, this link can help you with questions that you may have.

Global AuthenticationManager To create an AuthenticationManager that is available to the entire application you can simply register the AuthenticationManager as a @Bean.

Local AuthenticationManager In Spring Security 5.6 we introduced the method HttpSecurity#authenticationManager that overrides the default AuthenticationManager for a specific SecurityFilterChain. Below is an example configuration that sets a custom AuthenticationManager as the default:

@Configuration
public class SecurityConfiguration {

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

}
  • Related