Home > Enterprise >  Spring Security without the WebSecurityConfigurerAdapter and two AuthenticationProviders
Spring Security without the WebSecurityConfigurerAdapter and two AuthenticationProviders

Time:10-17

I have two AuthenticationProviders and don't know how to translate this to the new way of Spring Security. This is what I mean by "the new way" https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

Currently I'm extending WebSecurityConfigurerAdapter and have this configuration:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(inMemoryAuthenticationProvider);
    auth.authenticationProvider(ldapAuthenticationProvider);

    auth.userDetailsService(userDetailsService);
}

How must the configuration look like without extending WebSecurityConfigurerAdapter?

CodePudding user response:

How about this:

    @Configuration
    public class SecurityConfig {

        private AuthenticationManagerBuilder authBuilder;

        public SecurityConfig(AuthenticationManagerBuilder authBuilder) {
            this.authBuilder = authBuilder;
        }

        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            authBuilder.authenticationProvider(inMemoryAuthenticationProvider);
            authBuilder.authenticationProvider(ldapAuthenticationProvider);
            authBuilder.userDetailsService(userDetailsService);

            http
                    .authorizeHttpRequests((authz) -> authz
                            .anyRequest().authenticated()
                    )
                    .authenticationManager(authBuilder.getOrBuild())
                   .httpBasic(withDefaults());
            return http.build();
        }
    }

CodePudding user response:

I solved it by using filterChain as @Elyobek sugested but with this code:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authenticationProvider(inMemoryAuthenticationProvider);
    http.authenticationProvider(ldapAuthenticationProvider);
    http.userDetailsService(userDetailsService);
}

I didn't realize that I can set the AuthenticationProviders and UserDetailsService on HttpSecurity.

  • Related