[英]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()
受保护的方法中的loginByCookie()
yii\\web\\User
中调用。
还要重写此类,然后将user
组件配置中的类切换到您的自定义类。
3)以其他方式传递其他参数。 例如,使用Yii::$app->params
。 虽然似乎是一种黑客解决方案。
我个人建议使用第一种或第三种方法(以防您不赞成使用第一种方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.