基于条件切换Spring Security 5.7.11的LDAP与数据库认证
基于配置切换Spring Security数据库/LDAP认证方案
实现思路
通过Spring的条件注解@ConditionalOnProperty,根据配置项auth.type的值动态启用对应认证逻辑:
- 当
auth.type=ldap时,启用LDAP认证 - 其他情况(默认)启用数据库认证
具体实现步骤及代码修改
1. 读取配置参数
在SecurityConfig中注入配置项,默认值设为db:
@Configuration @EnableWebSecurity @EnableMethodSecurity public class SecurityConfig { @Value("${auth.type:db}") private String authType; // 原有Bean定义... }
2. 条件化注册数据库认证Provider
给数据库认证的AuthenticationProvider添加条件注解,仅当配置不为ldap时生效:
@Bean @ConditionalOnProperty(name = "auth.type", havingValue = "db", matchIfMissing = true) public AuthenticationProvider authenticationProvider(){ DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService()); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; }
3. 条件化配置LDAP认证
将LDAP认证逻辑包装在带条件注解的方法中,仅当auth.type=ldap时执行:
@Autowired @ConditionalOnProperty(name = "auth.type", havingValue = "ldap") public void configureLdapAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth .ldapAuthentication() .userDnPatterns("uid={0},ou=people") .groupSearchBase("ou=groups") .contextSource() .url("ldap://localhost:8389/dc=springframework,dc=org") .and() .passwordCompare() .passwordEncoder(passwordEncoder()) .passwordAttribute("userPassword"); }
4. 适配Spring Security 5.7+推荐写法(可选)
添加SecurityFilterChain统一配置认证入口:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .formLogin(form -> form .successHandler(customAuthenticationSuccessHandler()) ); return http.build(); }
配置说明
在application.properties中切换认证类型:
# 默认使用数据库认证 auth.type=db # 切换为LDAP认证 # auth.type=ldap
注意事项
- 确保
MuserDetailsService已正确实现数据库用户查询逻辑 - LDAP连接参数(url、userDnPatterns等)需根据实际环境调整
- 密码编码器保持统一,LDAP认证复用已定义的
BCryptPasswordEncoder
内容的提问来源于stack exchange,提问作者Ali Khalil
相关产品推荐
相关产品推荐

