spring-security Spring Security 5.7 -不带WebSecurityConfigurerAdapter多身份验证提供程序

mepcadol  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(331)

我使用的是Spring Security 5.7,WebSecurityConfigurerAdapter已弃用。我想使用多个身份验证提供程序(LDAP和Dao),但LDAP提供程序不工作,Spring Security只调用DaoAuthenticationProvider。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

@Autowired
private JWTTokenFilter jwtTokenFilter;

@Autowired
private LdapAuthProvider ldapAuthProvider;

@Autowired
private UserService userService;

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userService);
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .cors()
            .and().csrf().disable()
            .headers().frameOptions().disable()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests().antMatchers("/api/test/**", "/auth/**", "/h2-console/**").permitAll()
            .and().authorizeRequests().anyRequest().authenticated()
            .and().addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
    http.authenticationProvider(ldapAuthProvider);
    http.authenticationProvider(authenticationProvider());
    return http.build();
}

@Bean
public AuthenticationManager authenticationManager(
        AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

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

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source =
            new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

}

当删除DaoAuthenticationProvider时,LdapAuthProvider将正常工作。问题是什么?
编辑:我希望在整个应用程序中使用公开AuthenticationManager,如下所示:

@Autowired
private AuthenticationManager authenticationManager;

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) {

    if(authRequest.getUsername() == null || authRequest.getPassword() == null) {
        return ResponseEntity.badRequest().build();
    }

    Authentication authenticate = null;
    try {
        authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                authRequest.getUsername(),
                authRequest.getPassword()));
    } catch (Exception e) {

        e.printStackTrace();
        return ResponseEntity.status(401).build();
    }

但此身份验证管理器不包含我自定义身份验证提供程序

vshtjzan

vshtjzan1#

下面是一个在Spring Security 5.7中使用两个身份验证提供程序(Ldap和Dao)的示例。这是在使用表单登录的传统Web应用程序的上下文中。技巧是在过滤器链中显式设置要使用的AuthenticationManager(即ProviderManager),并引用这两个身份验证提供程序:

@Bean
public ActiveDirectoryLdapAuthenticationProvider getAdAuthProvider(CustomLdapUserDetailsMapper customLdapUserDetailsMapper) {
  ActiveDirectoryLdapAuthenticationProvider authProvider = new ActiveDirectoryLdapAuthenticationProvider(domain, urls);
  authProvider.setSearchFilter("(&(objectClass=user)(sAMAccountName={1}))");
  authProvider.setUserDetailsContextMapper(customLdapUserDetailsMapper);
  return authProvider;
}

@Bean
public DaoAuthenticationProvider getDaoAuthProvider(CustomDatabaseUserDetailsService customDatabaseUserDetailsService) {
  DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
  provider.setUserDetailsService(customDatabaseUserDetailsService);
  provider.setPasswordEncoder(new BCryptPasswordEncoder());
  return provider;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, ActiveDirectoryLdapAuthenticationProvider adAuthProvider, DaoAuthenticationProvider dbAuthProvider) throws Exception {
  http.authorizeRequests()
    .antMatchers("/").permitAll()
    ...
    .anyRequest().hasAuthority("ADMIN")
    .and().formLogin().loginPage("/login").permitAll()
    .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
    .and().authenticationManager(new ProviderManager(List.of(adAuthProvider, dbAuthProvider)));

  return http.build();
}

相关问题