针对两个不同的数据库表进行身份验证


Authenticating against two different database tables

我对 Yii 2.0 中的身份验证过程有点困惑。我正在开发一个具有两种用户(学生和讲师(的 Web 应用程序。每个实体都有自己的数据库表(MySQL,如果这很重要(,有自己的ID,用户名和密码字段。我已经查看了高级应用程序模板,其中包括针对数据库的身份验证,但在这种情况下,用户表是唯一的。就我而言,我必须能够确定要查找用户记录的数据库表(学生或讲师(。标识接口:

interface IdentityInterface
{
    /**
    * Finds an identity by the given ID.
    * @param string|integer $id the ID to be looked for
    * @return IdentityInterface the identity object that matches the given ID.
    * Null should be returned if such an identity cannot be found
    * or the identity is not in an active state (disabled, deleted, etc.)
    */
    public static function findIdentity($id);
    /**
    * Finds an identity by the given token.
    * @param mixed $token the token to be looked for
    * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
    * For example, [['yii'filters'auth'HttpBearerAuth]] will set this parameter to be `yii'filters'auth'HttpBearerAuth`.
    * @return IdentityInterface the identity object that matches the given token.
    * Null should be returned if such an identity cannot be found
    * or the identity is not in an active state (disabled, deleted, etc.)
    */
    public static function findIdentityByAccessToken($token, $type = null);
    /**
    * Returns an ID that can uniquely identify a user identity.
    * @return string|integer an ID that uniquely identifies a user identity.
    */
    public function getId();
    /**
    * Returns a key that can be used to check the validity of a given identity ID.
    *
    * The key should be unique for each individual user, and should be persistent
    * so that it can be used to check the validity of the user identity.
    *
    * The space of such keys should be big enough to defeat potential identity attacks.
    *
    * This is required if [[User::enableAutoLogin]] is enabled.
    * @return string a key that is used to check the validity of a given identity ID.
    * @see validateAuthKey()
    */
    public function getAuthKey();
    /**
    * Validates the given auth key.
    *
    * This is required if [[User::enableAutoLogin]] is enabled.
    * @param string $authKey the given auth key
    * @return boolean whether the given auth key is valid.
    * @see getAuthKey()
    */
    public function validateAuthKey($authKey);
}

包含不幸的是是静态的findIdentity()方法。我之所以这样说,是因为我在传递额外参数或从实现此接口的 app'models'User 类访问实例变量时遇到问题,该类将区分用户身份验证的数据库表。在我的情况下,findIdentity()中的$id参数不是唯一的。

我怎样才能找到解决方案?

我看到 3 个选项:

1(如果students表和lecturers表的结构没有绝对的不同,也许最好使用带有type列的公共表users。如果需要,您可以为它们使用不同的模型(请参阅此处(。

2(由于它是非通用且不广泛的方法,因此您可以覆盖核心类。

创建具有不同命名空间的IdentityInterface副本,并更改findIdentity()声明以满足您的需求。然后使用自定义界面而不是内置界面。

除了User模型之外,不要忘记搜索所有框架类以查找findIdentity()的用法,并将其替换为您的实现。

如我所见,它仅在loginByCookie()renewAuthStatus()受保护的方法中yii'web'User调用。

还要覆盖此类,然后将组件配置中的类切换user

自定义配置。

3( 以其他方式传递其他参数。例如,Yii::$app->params.不过似乎是一个黑客解决方案。

我个人建议使用第一种方法或第三种方法(如果您反对使用第一种方法(。