mindcontact-dev/yii2-ldap-auth

一个简单的库,用于在 Yii 2 应用程序中处理 LDAP 认证。由 stmswitcher/yii2-ldap-auth 衍生而来。

安装: 6

依赖者: 0

建议者: 0

安全性: 0

星标: 0

关注者: 0

分支: 4

类型:yii2-extension

0.1 2020-07-01 14:27 UTC

This package is auto-updated.

Last update: 2024-09-27 10:47:30 UTC


README

一个简单的扩展,用于在 Yii 2 应用程序中处理 LDAP 认证。

本扩展仅适用于依赖于 LDAP 认证的应用程序,不支持访问令牌。

安装

composer require "MindContact/yii2-ldap-auth:master"

配置示例和用例

考虑 yii2-app-basic

在配置文件中配置组件并更改用户身份类

'components' => [
    ...
    'ldapAuth' => [
        'class' => '\MindContact\Yii2LdapAuth\LdapAuth',
        'host' => 'ldap-server',
        'baseDn' => 'dc=shihadeh,dc=intern',
        'searchUserName' => 'cn=admin,dc=shihadeh,dc=intern',
        'searchUserPassword' => 'test1234',

        // optional parameters and their default values
        'ldapVersion' => 3,             // LDAP version
        'protocol' => 'ldap://',       // Protocol to use           
        'followReferrals' => false,     // If connector should follow referrals
        'port' => 389,                  // Port to connect to
        'loginAttribute' => 'cn',      // Identifying user attribute to look up for
        'ldapObjectClass' => 'inetOrgPerson',  // Class of user objects to look up for
        'timeout' => 10,                // Operation timeout, seconds
        'connectTimeout' => 5,          // Connect timeout, seconds
        'roleMappings' => [
            'cn=Admins,ou=Groups,dc=shihadeh,dc=intern' => 'admin',
            'cn=Maintaners,ou=Groups,dc=shihadeh,dc=intern' => 'operator',
        ],
        'isEnabled' => false,
        'demoUser' => [
            'Id' => 'demo.user',
            'Username' => 'Demo User',
            'Email' => 'demo.user@demo.com',
            'Dn' => 'cn=demo_user,dc=shihadeh,dc=intern',
            'Roles' => ['admin']
        ]
    ],
    ...
    
    'user' => [
        'identityClass' => '\MindContact\Yii2LdapAuth\Model\LdapUser',
        'enableSession' => true,
        'enableAutoLogin' => true,
    ],
    ...
]

更新 LoginForm 类中的方法

use MindContact\Yii2LdapAuth\Model\LdapUser;

...

public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = LdapUser::findIdentity($this->username);

        if (!$user || !Yii::$app->ldapAuth->authenticate($user->getDn(), $this->password) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

...

public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login(
            LdapUser::findIdentity($this->username),
            $this->rememberMe
                ? 3600*24*30 : 0
        );
    }
    return false;
}

验证用户是否属于 LDAP 群组

如果您还需要检查用户是否是特定 LDAP 群组的成员,请为 authenticate 函数添加一个额外的参数

Yii::$app->ldapAuth->authenticate($user->getDn(), $this->password, 'cn=auth-user-group')

现在您可以使用 LDAP 凭据登录到您的应用程序。