我正在 yii2 中进行用户登录,但不是使用活动记录,而是由另一台服务器处理用户用户名和密码的验证。因此,以下是我所做的解决方法:
in LoginForm.php
,我做了一些改变validatePassword()
which apiRest()
是我用来向负责验证的远程服务器发送请求的方法。
if (!$this->hasErrors()) {
$json = '{
"username": "' . $this->username . '",
"password": "' . $this->password . '"
}';
$response = $this->apiRest("POST", "104.130.126.68:3000/api/users/login", $json);
$user = $this->getUser();
if(!$user || isset($response['error'])) {
$this->addError($attribute, $response['error']['message']);
}
if(isset($response['data'])) {
$user->id = $response['data']['userId'];
$user->username = $this->username;
$user->ttl = $response['data']['ttl'];
$user->created = $response['data']['created'];
$user->accessToken = $response['data']['id'];
}
}
并且在LoginForm.php/getUser()
,我也做了一些修改:
if ($this->_user === false) {
$this->_user = User::createNewUser();
}
return $this->_user;
在哪里User.php
I have:
public static function createNewUser()
{
$user = [
'id' => '',
'username' => '',
'ttl' => '',
'created' => '',
'accessToken' => '',
];
return new static($user);
}
一切看起来都很好,我还可以打印出用户身份SiteController.php/actionLogin()
:
if ($model->load(Yii::$app->request->post()) && $model->login()) {
print('<pre>');
print_r(Yii::$app->user->identity->username);
die();
return $this->redirect(['set/index']);
} else {
$this->layout = "plain";
return $this->render('login', [
'model' => $model,
]);
}
但问题是,页面重定向后,用户身份就消失了;里面什么都没有Yii::$app->user->identity
。我错过了什么吗?请帮我。