【问题标题】:Use different AuthenticationProvider depending on username and remote IP address根据用户名和远程 IP 地址使用不同的 AuthenticationProvider
【发布时间】:2014-02-18 08:27:42
【问题描述】:

在基于 Spring Security 3.2 的应用程序中,我需要根据用户名和远程 IP 地址中的特定模式,针对两个不同的提供者对用户进行身份验证。

如果它们符合某些规则,则应根据ActiveDirectoryLdapAuthenticationProvider 对它们进行身份验证,否则使用标准AuthenticationProvider 使用UserDetailsService 的现有自定义实现。

我需要扩展什么? AuthenticationManagerAuthenticationProvider ?任何示例代码都将受到高度赞赏:-)

注意:我已经成功尝试在<authentication-manager /> 中添加两个<authentication-provider /> 节点,并且效果很好。但令我困扰的是,每次身份验证尝试都会命中我的 Ldap 服务器(即使是那些不适合它的)

【问题讨论】:

    标签: spring spring-security spring-ldap


    【解决方案1】:

    您可以创建一个包装器来检查模式/IP 地址是否匹配调用委托,否则返回 null。

    public class FilteringAuthenticationProvider implements AuthenticationProvider {
        private final AuthenticationProvider delegate;
    
        public FilteringAuthenticationProvider(AuthenticationProvider delegate) { this.delegate=delegate;}
    
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            Object details = authentication.getDetails();
            String username = authentication.getPrincipal().toString();
            String remoteAddress = null;
            if (details instanceof WebAuthenticationDetails) {
                remoteAddress = ((WebAuthenticationDetails) details).getRemoteAddress(); 
            }
    
            if (matches(remoteAddress, username)) {
                return delegate.authenticate(authentication);
            }
            return null
        }
    
        private boolean matches(String remoteAddress, String Username) {
            // your checking logic here
        }       
    }
    

    类似的东西。然后在你的安全配置中配置它并让它包裹ActiveDirectoryLdapAuthenticationProvider

    <sec:authentication-manager>
        <sec:authentication-provider ref="filteringLdapProvider" />
        <sec:authentication-provider>
            <user-service ref="customUserDetailsService" />
        </sec:authentication-provider>
    </sec:authentication-manager>
    
    <bean id="filteringLdapProvider" class="FilteringAuthenticationProvider">
        <constructor-arg ref="ldapProvider" />
    </bean>
    
    <bean id="ldapProvider" class="ActiveDirectoryLdapAuthenticationProvider">
    ...
    </bean>
    

    类似的东西。

    【讨论】:

    • 我是否正确理解 delegate.authenticate(authentication) 将有效地使用我的 UserDetailsS​​ervice 实现?如果 matches(remoteAddress, username) == false 我实例化一个 ActiveDirectoryLdapAuthenticationProvider 并将其传递给 authentication
    • 不...正如我提到的,您只需用这个包裹您的ActiveDirectoryLdapAuthenticationProvider。如果匹配为真,它只会实际调用ActiveDirectoryLdapAuthenticationProvider,否则返回null,这是Spring Security 调用链中下一个AuthenticationProvider 的触发器。
    • 查看修改后的答案。
    • 感谢您提供更多详细信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    相关资源
    最近更新 更多