簡體   English   中英

頁面重定向后Yii2用戶身份丟失

[英]Yii2 user identity loss after page redirection

我正在yii2中進行用戶登錄,但是不是使用活動記錄,而是由另一台服務器來處理用戶名和密碼的驗證。 因此,以下是我要做的工作:

LoginForm.php ,我對validatePassword()進行了一些更改,其中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我有:

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沒有任何內容。 我有想念嗎? 請幫我。

檢查您是否已在User.php實現yii\\web\\IdentityInterface

namespace app\models;

use yii\web\IdentityInterface;

class User implements IdentityInterface
{

}

如果是這種情況,請確保檢查Yii::$app->user->enableSessionTRUE默認情況下應為)。

好吧,驗證看起來不錯,但是您可以這樣做

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'];
    }

但是您永遠不會將用戶設置回模型。 我相信您應該在最后

$this->_user = $user;

您的登錄名可能看起來像這樣

/**
 * Logs in a user using the provided username and password.
 *
 * @return boolean whether the user is logged in successfully
 */
public function login()
{
    if ($this->validate()) {
        return $this->getUser()->login($this->rememberMe ? 2592000 : 0);
    } else {
        return false;
    }
}

getUser將再次不返回任何內容(它將返回您創建的空用戶),因為您從未真正對其進行過設置。

也是行長說的話,我希望這不用多說:)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM