cyllenea/multiple-ldap

多重LDAP认证器

dev-master 2021-09-30 09:23 UTC

This package is auto-updated.

Last update: 2024-09-29 05:22:28 UTC


README

这个简单的库用于在多个LDAP/AD服务器上进行自动认证。

如果在一个服务器上的登录不成功,它会尝试在另一个服务器上登录。

通常用于企业环境中的全局应用程序,其中存在多个具有各自AD服务器的不同地点。

库注册

extensions:
    ldap: cyllenea\multiple-ldap\LDAPExtension

设置要从Active Directory记录中获取的属性

ldap:
    attributes:
        - employeeNumber    # Employee ID
        - employeeID        # Cost center
        - mail              # Email address
        - cn                # Common name
        - sn                # Surname
        - givenName         # First name

设置认证服务器

ldap:
    controllers:
        wnc:
            host: wnc.local
            port: 389
            domain: "%s@wnc.local"
            dn: "OU=COMPANY,DC=wnc,DC=local"

        wv:
            host: wvdc01.wv.local
            port: 389
            domain: "%s@wv.local"
            dn: "OU=COMPANY,DC=wv,DC=local"

注册自定义授权服务

services:
    authenticator:
        class: cyllenea\multiple-ldap\Authenticator
        setup:
            - setIdentityGenerator([@userManagemenent, 'createIdentity'])

自定义授权服务实现示例

<?php declare(strict_types = 1);

namespace App\Model\Security\Authenticator;

use cyllenea\ldap\Exception\LDAPErrorException;
use cyllenea\ldap\LDAP;
use Nette;

final class UserAuthenticator implements Nette\Security\IAuthenticator
{

    private LDAP $ldap;

    public function __construct(LDAP $ldap)
    {
        $this->ldap = $ldap;
    }

    public function authenticate(array $credentials): Nette\Security\IIdentity
    {
        [$username, $password] = $credentials;

        $user = null;

        $attributes = [];

        try {

            // Login to LDAP
            $this->ldap->login($username, $password);

            // Search user
            $obtainedAttributes = $this->ldap->search($username);

            // Get attributes
            $attributes = Nette\Utils\ArrayHash::from($this->ldap->parseAttributes($obtainedAttributes));

        } catch (LDAPErrorException | \Exception $e) {

            throw new Nette\Security\AuthenticationException('Authentication failed. Please check your username/password.');

        } finally {

            // Disconnect
            $this->ldap->disconnect();

        }

        return new Nette\Security\Identity($username, [], $attributes);
    }

}

登录

try {
    $this->user->login("USERNAME", "PASSWORD");
    return true;
} catch (AuthenticationException $e) {
    // Něco se pokazilo, pop.ř. - dump($e->getMessage());
}