在不使用xml配置的情况下而不是通过Java代码创建委托的LdapAuthenticationProvider

问题描述

我想编写一个自定义的LdapAuthenticationProvider,如下所示:

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        LdapAuthenticationProvider ldap = new LdapAuthenticationProvider(); // don't kNow how to do 
                                                                                  instantiate this 
        Authentication authentication1 = super.authenticate(authentication);
       return new LdapToken(null,null,"",true,"");
   }

我的意图是将身份验证委派给认的LdapAuthenticationProvider,但在身份验证后返回一些自定义令牌。

但是我无法创建LdapAuthenticationProvider的对象,因为实际上返回LdapAuthenticationProvider的对象的LdapAuthenticationProviderConfigurer的构建方法是私有的。而且我不想使用XML配置文件来做到这一点。

有人可以让我知道如何做到这一点吗?

解决方法

您需要使用AuthenticationManager,而不是直接调用LdapAuthenticationProvider

您需要在配置中将其公开为可注入bean:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

假设您的LdapAuthenticationProvider是可检测的Bean,AuthenticationManager将自动注入其中。