Spring security Spring安全多提供商中断

Spring security Spring安全多提供商中断,spring-security,Spring Security,我有一个带有多个提供者的spring安全配置,它运行良好。 但如果无法访问其中一个提供程序,则会引发异常并停止身份验证 例如: Login with credentials user/user: A) - provider1 -> OK (reacheable but no account user/user) B) - provider2 -> NOT OK (non reachable) C) - provider 3 -> OK (reachable and has ac

我有一个带有多个提供者的spring安全配置,它运行良好。 但如果无法访问其中一个提供程序,则会引发异常并停止身份验证

例如:

Login with credentials user/user:
A) - provider1 -> OK (reacheable but no account user/user)
B) - provider2 -> NOT OK (non reachable)
C) - provider 3 -> OK (reachable and has account user/user)
它在步骤B停止,因为提供者没有响应。我想处理在步骤B抛出的异常,并继续与提供者3进行成功的身份验证


有可能吗?

如果您检查API文档中的
AuthenticationProvider
,您可以选择返回null,而不是引发异常,这将导致您想要的行为


因此,要么修改实现,要么使用委托来包装现有的提供程序,捕获异常并返回null。您应该只捕获表示系统故障的异常,而不是实际的
身份验证异常
,该异常表明提供的身份验证信息不正确。

对于可能感兴趣的人,我的解决方案如下:

package fr.test.myapp.core.security.ldap;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ldap.NamingException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.authentication.LdapAuthenticator;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;

@Slf4j
public class CustomLdapAuthenticationProvider extends LdapAuthenticationProvider{

    public CustomLdapAuthenticationProvider(LdapAuthenticator authenticator, LdapAuthoritiesPopulator authoritiesPopulator) {
        super(authenticator, authoritiesPopulator);
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        try {
            return super.authenticate(authentication);
        }catch(InternalAuthenticationServiceException ex){
            NamingException ldapAccessFailure = (NamingException)ex.getCause();
            log.warn("Impossible to connect to the LDAP server. This ldap provider is ignored, continues with the next one: Error cause: {}",
ldapAccessFailure.getMessage(),ex.getMessage());
            return null;
        }

    }
}