我的用户授权在没有authKey
的情况下工作正常。我不知道我应该如何使用它。但是在文档中使用它在某种程度上更安全。我已经在用户活动记录类中实现了此方法。
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
我什至在用户创建时将其保存到用户表中。但我知道validateAuthKey
从未被使用过。我正在使用会话,只有PHPSESSID发送给用户。我必须手动设置authKey
饼干吗?这样做有什么好处?为什么我不能只通过PHPSESSID授权用户。它已存储在会话表中。会话配置:
'session' => [
'class' => 'yiiwebDbSession',
'sessionTable' => 'session',
],
Yii2 中已经有一个答案:为什么类 User 中的身份验证密钥?
请参阅以下源代码 ( vendoryiisoftyii2webUser.php
):
protected function loginByCookie()
{
$value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
if ($value === null) {
return;
}
$data = json_decode($value, true);
if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) {
return;
}
list ($id, $authKey, $duration) = $data;
/* @var $class IdentityInterface */
$class = $this->identityClass;
$identity = $class::findIdentity($id);
if ($identity === null) {
return;
} elseif (!$identity instanceof IdentityInterface) {
throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
}
if ($identity->validateAuthKey($authKey)) {
if ($this->beforeLogin($identity, true, $duration)) {
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
$ip = Yii::$app->getRequest()->getUserIP();
Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
$this->afterLogin($identity, true, $duration);
}
} else {
Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
}
}