Spring安全多个提供商中断

时间:2014-07-18 17:24:48

标签: 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 account user/user)

它在步骤B停止,因为提供者没有响应。我想处理在步骤B抛出的异常,然后继续对提供者3进行成功的身份验证。

有可能吗?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

对于那些可能感兴趣的人,这是我的解决方案:

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;
        }

    }
}
相关问题