magicmaster0511 / yii2-ldap-auth
处理Yii 2应用程序中LDAP认证的简单库。
1.4.1
2024-09-27 19:41 UTC
Requires
- php: >= 8.3
- ext-ldap: *
- yiisoft/yii2: ~2.0.14
README
这是一个处理Yii 2应用程序中LDAP认证的简单扩展。
此扩展旨在仅依赖LDAP认证的应用程序,不支持访问令牌。
安装
composer require "magicmaster05111/yii2-ldap-auth"
配置示例和用例
在配置文件中配置组件并更改用户身份类
'components' => [ ... 'ldapAuth' => [ 'class' => '\stmswitcher\Yii2LdapAuth\LdapAuth', 'host' => 'your-ldap-hostname', 'baseDn' => 'dc=work,dc=group', 'searchUserName' => '<username for a search user>', 'searchUserPassword' => '<password for a search user>', // optional parameters and their default values 'ldapVersion' => 3, // LDAP version 'protocol' => 'ldaps://', // Protocol to use 'followReferrals' => false, // If connector should follow referrals 'port' => 636, // Port to connect to 'loginAttribute' => 'uid', // Identifying user attribute to look up for 'ldapObjectClass' => 'person', // Class of user objects to look up for 'timeout' => 10, // Operation timeout, seconds 'connectTimeout' => 5, // Connect timeout, seconds ], ... 'user' => [ 'identityClass' => '\stmswitcher\Yii2LdapAuth\Model\LdapUser', ], ... ]
更新LoginForm类中的方法
use stmswitcher\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凭据登录到您的应用程序。
使用访问控制过滤器
如果您想使用访问控制过滤器,可以使用LdapManager类作为认证管理器
return [ 'components' => [ 'authManager' => [ 'class' => 'stmswitcher\Yii2LdapAuth\LdapManager', ], ], ];
接下来,指定需要授权访问操作的动作组列表
public function behaviors() { return [ 'access' => [ 'class' => AccessControl::class, 'rules' => [ [ 'allow' => true, 'roles' => ['group1', 'group2'], ], ], ], ]; }