使用Spring Security在运行时切换身份验证方法?

Jay*_*Jay 6 java authentication spring spring-security java-ee

通常,当您为应用程序声明不同的"<authentication-provider>"(在我的情况下为webapp)时,Spring Security将负责一个接一个地调用提供程序,这会导致失败.因此,假设我在配置文件中首先声明了DatabaseAuthenticationProvider和LDAPAuthenticationProvider,并且在运行时首先调用DatabaseAuthenticationProvider,如果身份验证失败,则尝试LDAPAuthentication.这很酷 - 但是,我需要的是运行时切换.

我想有一个选择在这两种方法之间选择(基于数据库的身份验证/基于ldap的身份验证),并以某种方式基于这个全局设置来实现实现.

我该怎么做?是否可以使用Spring-Security?

Mat*_*att 5

如何编写一个委托 AuthenticationProvider 来知道如何访问运行时开关和 Database/LDAP AuthenticationProvider 的实际实例。

我在想这样的事情:

public class SwitchingAuthenticationProvider implements AuthenticationProvider
{
    private List<AuthenticationProvider> delegateList;
    private int selectedProvider;

    @Override
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException
    {
        AuthenticationProvider delegateTo = delegateList.get(selectedProvider);
        return delegateTo.authenticate(authentication);
    }

    ....
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 5

我将把如何注入您自己的自定义身份验证提供程序留给Googleland和StackOverflow上的其他无数示例。看起来它与用 xml 标记特定的 bean 有关。但希望我能为您填写一些其他详细信息。

因此,您已经定义了类似于上面的类,我将添加 Spring 所需的更多详细信息(即也合并上面的内容)。

public class SwitchingAuthenticationProvider implements AuthenticationProvider
{
    ....
    public List<AuthenticationProvider> getProviders() { return delegateList; }
    public void setProviders(List<AuthenticationProvider> providers) {
        this.delegateList = providers;
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

这将允许您使用 spring 注入大量提供者:

<bean id="customAuthProvider1" class=".....CustomProvider1"> ... </bean>
<bean id="customAuthProvider2" class=".....CustomProvider2"> ... </bean>
...
<bean id="customAuthProviderX" class=".....CustomProviderX"> ... </bean>

<bean id="authenticationProvider" class="....SwitchingAuthenticationProvider">
    <security:custom-authentication-provider/>
    <!-- using property injection (get/setProviders) in the bean class -->
    <property name="providers">
        <list>
            <ref local="customAuthProvider1"/> <!-- Ref of 1st authenticator -->
            <ref local="customAuthProvider2"/> <!-- Ref of 2nd authenticator -->
            ...
            <ref local="customAuthProviderX"/> <!-- and so on for more -->
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

最后,填充提供者的方式可以是让委托者获得提供者集合的任何方法。它们如何映射到使用哪一个取决于您。该集合可以是基于委托者当前状态的命名映射。它可能是一个包含多个尝试的列表。它可以是两个属性,“get/setPrimary”和“get/setSecondary”,用于类似故障转移的功能。一旦您注入了委托人,可能性就取决于您了。

如果这不能回答您的问题,请告诉我。