Spring Boot 对身份验证提供程序设置条件

t5zmwmid  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(63)

我使用的是spring security 5.7.11,我有以下代码。我可以使用数据库进行身份验证,单独使用时使用ldap如何根据条件进行身份验证。例如,如果auth.type=ldap,则使用ldap,否则使用数据库。

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        return new MuserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }
    @Bean
    public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
        return new CustomAuthenticationSuccessHandler();
    }
    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
    @Autowired
    public void configure(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(new BCryptPasswordEncoder())
                    .passwordAttribute("userPassword");
    }

}

字符串

0lvr5msh

0lvr5msh1#

在您的学习类上使用@ConditionalOnProperty
举例说明:

@Configuration
@ConditionalOnProperty(prefix="auth", name="type", havingValue="db", matchIfMissing=true)
// default configuration due to matchIfMissing=true
public class DataBaseSecurityConfig {
 // your DB related Beans
}

/* and */

@Configuration
@ConditionalOnProperty(prefix="auth", name="type", havingValue="ldap")
public class LdapBaseSecurityConfig {
 // your LDAP related Beans
}

字符串
@Bean上的@ConditionalOnProperty a
举例说明:

@Bean
 @ConditionalOnProperty(prefix="auth", name="type", havingValue="db", matchIfMissing=true)
 //Bean creation if auth.type=db or auth.type is not provided
  public AuthenticationProvider authenticationProvider(){
    ...;
 }


也可以使用@Value
示例:@Value(“${auth.type:db}”) 其中“db”是默认值(如果未提供值)

@Autowired
public void configure(@Value("${auth.type:db}") String type, AuthenticationManagerBuilder auth){
 if("db".equals(type) {
  ....
 } else {
  ....
 }
}

相关问题