在 Spring Security 中同时使用 LDAP 和 DB 身份验证

DTn*_*paT 5 authentication spring-mvc spring-security

我有一个应用程序,供公司和外部客户的两组用户使用。我必须对两组用户进行身份验证。应用程序将使用 Spring Security 构建。对于内部用户,需要进行LDAP AD认证,对于外部用户,需要从数据库进行认证。我被困在这里。

如何使用两种类型的身份验证?可以根据用户的电子邮件 ID 区分用户 - 例如,内部用户的电子邮件 ID 都以 @company.com 结尾。

  1. 在 spring 安全配置中,可以这样做吗?-

    <authentication-manager>
            <authentication-provider>
                <ldap-authentication-provider....>
                <db-authentication-provider......>  
            </authentication-provider>
    <authentication-manager>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 那么我是否应该编写一个过滤器(在 spring security 过滤器之前),根据用户的登录电子邮件 ID 选择用户并将他们定向到正确的身份验证管理器?这种重定向可以在这里完成吗?

我是新手。提前致谢。

DTn*_*paT 4

我很久以前就问过这个问题。我在整合资源后实现了这一点。随着时间的推移,我已经忘记了这个话题。奇怪的是时间过得真快!!无论如何,我只是回来分享这个问题的答案。实现此解决方案的一种方法是使用多个身份验证提供程序

由于最初的问题是使用基于 XML 的配置,因此我将继续讨论。(我自己现在使用基于Java的配置。稍后将尝试在此处添加基于Java的解决方案)。

因此,首先在 security.xml 中添加以下内容 - spring security 的主要配置文件。

<authentication-manager>            
    <authentication-provider ref="customJdbcAuthProvider" />
    <authentication-provider ref="customLdapAuthProvider" />            
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)

接下来需要将 2 个 bean 添加到 security.xml 中,以实现支持功能。

security.xml 中的条目:

<bean:bean id="customJdbcAuthProvider" class="com.springapp.myapp.setup.CustomJdbcAuthProvider" />
<bean:bean id="customLdapAuthProvider" class="com.springapp.myapp.setup.CustomLdapAuthProvider" />
Run Code Online (Sandbox Code Playgroud)

最后是豆子本身。该Bean应该实现org.springframework.security.authentication.AuthenticationProvider接口。

public class CustomJdbcAuthProvider implements AuthenticationProvider {
@Override
    public Authentication authenticate(Authentication authObj)
            throws AuthenticationException {    

            // code snippet to authenticate against DB
            }

            }
}
Run Code Online (Sandbox Code Playgroud)

以及相应的bean来处理Ldap认证。我使用了这个 bean 的扩展 org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider 接口。Spring 还提供了其他 API 实现。

public class CustomActiveDirectoryLdapAuthenticationProvider extends AbstractLdapAuthenticationProvider {
  // code snippet to authenticate and authorize against company or local LDAP or Active Directory.
}
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题并让你跑步!如果您需要更多详细信息,请告诉我。