首页 文章

Symfony2:使用LDAP(Active Directory)和DB进行用户身份验证

提问于
浏览
8

我正在使用Symfony框架 v 2.4.2 更新现有网站,该网站执行双重检查以记录用户:

  • 首先,它检查用户名和密码是否属于有效的Active Directory用户(使用PHP的 ldap_bind() 函数);

  • 如果是,则检查 the username only 对数据库表(DB中的 no password is stored );

  • 如果在DB表中找到用户名,则网站从DB加载用户配置文件,并对用户进行身份验证 .

How can I replicate this auth process in Symfony2?

到目前为止,我遇到了FOSUserBundle和FR3DLdapBundle:我设法使用链式提供程序( ldapdb ),但看似完全忽略了LDAP凭据:用户可以使用存储在数据库中的凭据登录,即使 ldap_bind() 失败 - 这是第1点和第2点的确切 opposite .

此外,在使用FOSUserBundle时,似乎必须将密码存储在DB中 .

pay attention to point no. 2: 用户必须可以自由地从网站外部(即从Active Directory)更改其LDAP密码,然后使用新凭据登录,而无需更新网站的用户数据库 .

任何解决方案都是受欢迎的,我不太喜欢FOSUserBundle,更不喜欢FR3DLdapBundle .

2 回答

  • 3

    我这样做了:

    • 基于FOSUSerBundle用户模型创建了自定义用户实体;

    • 创建了一个自定义用户提供程序(请参阅Javad对此问题的回答),将其注册为服务并将其添加到 app/config/security.yml 中的 providers 部分;

    • 从v2.4开始,Symfony(幸运的是)提供了一个简化的身份验证系统,它不会强迫您通过所有自定义身份验证提供程序(IMHO真的很痛苦):它被称为Authenticator,它记录在案here . 我实现了自己的Authenticator类,并使用我的自定义UserProvider类执行了双重检查 .

  • 4

    您需要为LDAP定义一个CustomUserProvider,它将在AD和您的security.yml中找到该用户,您需要设置此提供程序(Custom User Provider

    providers:
        ldap_provider:
            id: myprovider.security.user.provider   # as you know when you create a custom web service provider you need to define it as a service and use the ID of the service here #
    

    您还需要在防火墙中启用服务
    下一步是为LDAP创建自定义身份验证提供程序,通过LDAP对用户和密码进行身份验证,并从DB返回用户对象(Custom Authentication Provider

    首先基于此过程,它将尝试在LDAP中查找用户(如果存在),它将继续通过LDAP进行身份验证,如果用户已通过身份验证,则将从DB返回用户对象

    以下是自定义用户提供程序的示例

    public function loadUserByUsername($username)
    {
       $ldap_obj = new adLDAP('exampl.ldapdircetory.com', 'prot', 'Base_DN', 'ldap_admin_user', 'ldap_admin_pass'));
       $filter = "( &(objectclass=person)( |(uid=".$username.")(cn=".$username.")(mail=".$username.") ) )";
       $info = $ldap_obj->search_user($filter);
       if ($info['count'] != 0) {
          // create temp User instance of UserInterface base on the returned info
          $user = new User();
          ...
          return $user
       }
       else {
          throw new UsernameNotFoundException('No match username was found.');
       }
    

    我假设您有adLDAP类来通过LDAP对用户进行身份验证

相关问题