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

t5zmwmid  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(162)

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

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableMethodSecurity
  4. public class SecurityConfig {
  5. @Bean
  6. public UserDetailsService userDetailsService() {
  7. return new MuserDetailsService();
  8. }
  9. @Bean
  10. public PasswordEncoder passwordEncoder() {
  11. return new BCryptPasswordEncoder(12);
  12. }
  13. @Bean
  14. public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
  15. return new CustomAuthenticationSuccessHandler();
  16. }
  17. @Bean
  18. public AuthenticationProvider authenticationProvider(){
  19. DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
  20. authenticationProvider.setUserDetailsService(userDetailsService());
  21. authenticationProvider.setPasswordEncoder(passwordEncoder());
  22. return authenticationProvider;
  23. }
  24. @Autowired
  25. public void configure(AuthenticationManagerBuilder auth) throws Exception {
  26. auth
  27. .ldapAuthentication()
  28. .userDnPatterns("uid={0},ou=people")
  29. .groupSearchBase("ou=groups")
  30. .contextSource()
  31. .url("ldap://localhost:8389/dc=springframework,dc=org")
  32. .and()
  33. .passwordCompare()
  34. .passwordEncoder(new BCryptPasswordEncoder())
  35. .passwordAttribute("userPassword");
  36. }
  37. }

字符串

0lvr5msh

0lvr5msh1#

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

  1. @Configuration
  2. @ConditionalOnProperty(prefix="auth", name="type", havingValue="db", matchIfMissing=true)
  3. // default configuration due to matchIfMissing=true
  4. public class DataBaseSecurityConfig {
  5. // your DB related Beans
  6. }
  7. /* and */
  8. @Configuration
  9. @ConditionalOnProperty(prefix="auth", name="type", havingValue="ldap")
  10. public class LdapBaseSecurityConfig {
  11. // your LDAP related Beans
  12. }

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

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


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

  1. @Autowired
  2. public void configure(@Value("${auth.type:db}") String type, AuthenticationManagerBuilder auth){
  3. if("db".equals(type) {
  4. ....
  5. } else {
  6. ....
  7. }
  8. }

展开查看全部

相关问题