spring-security 没有WebSecurityConfigurerAdapter和两个身份验证提供程序的Spring安全性

kwvwclae  于 2022-11-11  发布在  Spring
关注(0)|答案(2)|浏览(326)

我有两个AuthenticationProviders,但不知道如何将其转换为Spring Security的新方式。
目前我正在扩展WebSecurityConfigurerAdapter,并具有以下配置:

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

    auth.userDetailsService(userDetailsService);
}

在不扩展WebSecurityConfigurerAdapter的情况下,配置应该是什么样子?

toiithl6

toiithl61#

我通过使用filterChain来解决这个问题,就像@Elyobek建议的那样,但是代码如下:

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

我没有意识到我可以在HttpSecurity上设置AuthenticationProvidersUserDetailsService

gzszwxb4

gzszwxb42#

不如这样吧:

@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();
        }
    }

相关问题