如何基于LDAP和JDBC之间的用户选择在Spring Security中实现条件身份验证?

问题描述

希望大家都做的很好,很安全。我有一个应用程序,该应用程序将允许用户使用其LDAP凭据或存储在数据库中的凭据登录。我能够配置单独的jdbc和ldap身份验证器,但是如何有条件地实现它呢?假设用户选择登录页面上的LDAP单选按钮,则应触发LDAP身份验证,如果用户选择数据库身份验证,则应触发jdbc身份验证。任何帮助将不胜感激。

JDBC身份验证器:-

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;
    
    @Override
     public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Todo Auto-generated method stub
        
         http.authorizeRequests()
         .antMatchers("/admin").hasAnyRole("ADMIN")
         .antMatchers("/user").hasAnyRole("ADMIN","USER")
         .antMatchers("/").permitAll()
         .and().formLogin();
    }
    
    @Bean
    public PasswordEncoder getpasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

**LDAP authenticator:-**

@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AuthenticationFailureHandler() {
            String message = "";

            @Override
            public void onAuthenticationFailure(HttpServletRequest request,HttpServletResponse response,AuthenticationException exception) throws IOException,servletexception {

                if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
                    message = "User Not Found";
                } else if (exception.getClass().isAssignableFrom(disabledException.class)) {
                    message = "Account disabled";

                } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
                    message = "Bad Credentials";
                }
                else if (exception.getClass().isAssignableFrom(LockedException.class)) {
                    message = "Account Locked";
                }
                else {
                    message = "Internal Server Error";
                }
                response.sendRedirect("/WisoKeyinPortal/login?error=" + message);

            }  
        };
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return super.userDetailsService();
    }
 
    @Bean
    public AuthenticationProvider authProvider() {

        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();

        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());

        return authenticationProvider;

    }

    /*---------------------------For QA comment from here-------------------------------*/
    
      @Bean public AuthenticationManager authenticationManager() { return new
      ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
      }
      
      @Bean public AuthenticationProvider
      activeDirectoryLdapAuthenticationProvider() {
      ActiveDirectoryLdapAuthenticationProvider provider = new
      ActiveDirectoryLdapAuthenticationProvider("xyz.com","ldap://xyz.com");
      provider.setConvertSubErrorCodesToExceptions(true);
      provider.setUseAuthenticationRequestCredentials(true);
      provider.setSearchFilter("sAMAccountName={1}"); return provider; }
     
    /*----------------------------For QA comment ends here-----------------------------*/
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] staticResources = { "/css/**","/images/**","/fonts/**","/scripts/**",};

        http.csrf().disable().authorizeRequests().antMatchers("/login**").permitAll().antMatchers(staticResources)
                .permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll()
                .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler).and()
                .logout().invalidateHttpSession(true).clearauthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").permitAll();
                //.and().sessionManagement().invalidSessionUrl("/login?error=session");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {

        //authManagerBuilder.inMemoryAuthentication().withUser("admin").password("pass").roles("ADMIN");
        
        /*---------------------------For QA comment from here-------------------------------*/
        
          authManagerBuilder.authenticationProvider(
          activeDirectoryLdapAuthenticationProvider())
          .userDetailsService(userDetailsService());
         
        /*---------------------------For QA comment from here-------------------------------*/
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...