簡體   English   中英

Yii2用戶身份登錄后得到null

[英]Yii2 user identity gets null after login

我有一個 Yii2 應用程序,我在其中驗證來自第三方 API 的用戶,一旦用戶通過身份驗證,然后我登錄用戶並設置身份,一切正常。 但是當我導航到任何其他頁面時,用戶身份獲得 null 並且用戶成為來賓用戶。

這是我的登錄表單:

<?php

namespace app\models;

use app\components\RestBehavior;
use app\models\web\LoginIdentity;
use Yii;
use yii\base\Model;
use yii\helpers\Json;
use yii\helpers\VarDumper;
use yii\web\IdentityInterface;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $email;
    public $password;
    public $company_id;
    public $companies=[];
    public $token;

    private $_user = false;


    public function behaviors()
    {
        return [
            RestBehavior::class
        ];
    }

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['email', 'password','company_id'], 'required'],
        ];
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        return Yii::$app->user->login($this->getUser(), 0);
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = LoginIdentity::findUser($this->attributes);
        }
        return $this->_user;
    }

}

這是我的自定義 LoginIdentity class:

<?php

namespace app\models\web;

use app\components\RestBehavior;
use \Yii;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\helpers\VarDumper;

class LoginIdentity extends \yii\base\BaseObject implements \yii\web\IdentityInterface
{
    public $resource_id;
    public $token;

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            RestBehavior::class
        ];
    }

    public static function findUser($params)
    {
        if(!empty(Yii::$app->user->identity))
        {
            return new static([
                'resource_id'=>self::getId(),
                'token'=>self::getAuthKey()
            ]);
        }
        else
        {
            Yii::$app->controller->sendPOST('/login',$params);
            if(Yii::$app->response->statusCode===200)
            {
                $response=Json::decode(Yii::$app->response->data);
                $identity=new static([
                    'resource_id'=>$response['resource']['resource_id'],
                    'token'=>$response['token']
                ]);
                Yii::$app->session->set('resource_id',$response['resource']['resource_id']);
                Yii::$app->session->set('token',$response['token']);
                return $identity;
            }
            return null;
        }

    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        $session=Yii::$app->session;
        if(!empty($session['resource_id'])&&!empty($session['token']))
        {
            return new static([
                'resource_id'=>$session['resource_id'],
                'token'=>$session['token']
            ]);
        }
        return null;
    }

    /**
     * {@inheritdoc}
     * @param \Lcobucci\JWT\Token $token
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {

    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->resource_id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->token;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
    }
}

非常奇怪的是,整個代碼在我的本地計算機(即本地主機)上運行良好。 但是在服務器上,用戶登錄但在訪問任何新的經過身份驗證的路由時注銷。 我檢查了服務器的 /var/lib/php/sessions 文件夾,session 被正確保存,所以沒有權限問題。 誰能告訴我這里出了什么問題? 為什么它在我的本地計算機上工作而不是遠程工作。 謝謝你。

這與 Yii2 或 Identity 類實現無關。 代碼在各方面都是正確的。 原因是我的服務器將cookie_secure設置為 true,這意味着該會話只能在 SSL 上建立,但我試圖在不安全的來源(即 http)上登錄。 此外,我的網站正在使用 SSL,但當頁面加載時,由於網站圖標路徑無效,它變成了不安全或 http。 因此,firefox 瀏覽器在控制台中顯示,當客戶端在 HTTP 上運行時,cookie 被服務器拒絕,而 Chrome 的控制台則對幕后發生的事情保持沉默。

感謝 Hammad 的回答,沒有其他人給我真正的解決方案,但我在“web.php”配置文件中解決了它,只是將參數“secure”=> true 更改為 false。 原因是我使用了 http 而不是 https(無 SSL),我使用了這個臨時解決方案:

'session' => [
 'cookieParams' => [
            'secure' => false,
    ],
],

暫無
暫無

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

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