创建委托 LdapAuthenticationProvider 而不使用 xml 配置,而不是通过 java 代码

Posted

技术标签:

【中文标题】创建委托 LdapAuthenticationProvider 而不使用 xml 配置,而不是通过 java 代码【英文标题】:Creating a delegating LdapAuthenticationProvider without using xml configuration, rather by java code 【发布时间】:2020-12-07 12:13:46 【问题描述】:

我想写一个自定义的 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 的对象,因为 LdapAuthenticationProviderConfigurer 的构建方法实际上返回 LdapAuthenticationProvider 的对象是私有的。而且我不想使用 XML 配置文件。

谁能告诉我如何做到这一点?

【问题讨论】:

【参考方案1】:

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

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

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

假设您的 LdapAuthenticationProvider 是一个可检测的 Bean,AuthenticationManager 将自动注入它。

【讨论】:

那它怎么知道它必须调用 LdapAuthenticationProvider 认证方法呢?这是 spring security 本身提供的一个类。我想保留默认的 ldap 提供程序,但最后我想返回我自己的类型令牌。我也有自己的过滤器和令牌类。但面临与提供商的问题

以上是关于创建委托 LdapAuthenticationProvider 而不使用 xml 配置,而不是通过 java 代码的主要内容,如果未能解决你的问题,请参考以下文章

创建一个对象作为委托 - Objective C

C# 笔记——委托

C# 委托及各种写法

委托和事件

委托创建 ViewController 的新实例

如何从 MethodInfo 创建 Action 委托?