我使用的是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();
}
但此身份验证管理器不包含我自定义身份验证提供程序
1条答案
按热度按时间vshtjzan1#
下面是一个在Spring Security 5.7中使用两个身份验证提供程序(Ldap和Dao)的示例。这是在使用表单登录的传统Web应用程序的上下文中。技巧是在过滤器链中显式设置要使用的
AuthenticationManager
(即ProviderManager
),并引用这两个身份验证提供程序: