User authentication not working

Hi,

I started a new Yii2 app and it looks like something is not configured correctly. After I login the php session cookie is set (e.g. "1r3vsg8v1ec3ufmknn9kf6pt74"). My app is configured to store the session in the DB and that also appear to work correctly. After logging in, I see this in the session table:


    ID                          EXPIRE      DATA

    1r3vsg8v1ec3ufmknn9kf6pt74	1467052571	__flash|a:0:{}__id|i:2;

So the login part seems to be working correctly. The problem happens when I redirect to a different controller after login (e.g. "test/index"). The "index" method looks like this:


	public function actionIndex()

    {

		Yii::warning(Yii::$app->user->identity);

		return $this->render('index');

    }

“Yii::$app->user->identity” is returning NULL. Does anyone know what I’m doing wrong? I’ve been looking for hours but I can’t figure where exactly the identity is supposed to be loading and why it isn’t working properly.

Typically Identity is loaded in login action on successful login, but depends on your code or the extension you use

http://www.yiiframew…html#using-user

In few words once you verified the user and password successfully you need to initialize the identity

Note User is a special user model that implement the Identity class




// find a user identity with the specified username.

// note that you may want to check the password if needed

$identity = User::findOne(['username' => $username]);


 // logs in the user 

Yii::$app->user->login($identity);



The second row of code is the one that start the user session in your app and make Yii::$app->user->identity

If you use an extension just search the extension code for Yii::$app->user->login

Yes, I understand that the Identity is first loaded after login and that seems to work correctly. If I run this "Yii::warning(Yii::$app->user->identity);" right after the login, I can see the correct data.

If I run a different controller, where/when is the Identity loaded in that new controller? That part isn’t working yet.

Hi Littlebob,

Look to this code (or debug it) maybe could help you to determine your problem. This is how your identity is searched and/or renewed when not found:




// inside yii\web\User


    /**

 	* Returns the identity object associated with the currently logged-in user.

 	* When [[enableSession]] is true, this method may attempt to read the user's authentication data

 	* stored in session and reconstruct the corresponding identity object, if it has not done so before.

 	* @param boolean $autoRenew whether to automatically renew authentication status if it has not been done so before.

 	* This is only useful when [[enableSession]] is true.

 	* @return IdentityInterface|null the identity object associated with the currently logged-in user.

 	* `null` is returned if the user is not logged in (not authenticated).

 	* @see login()

 	* @see logout()

 	*/

    public function getIdentity($autoRenew = true)

    {

        if ($this->_identity === false) {

            if ($this->enableSession && $autoRenew) {

                $this->_identity = null;

                $this->renewAuthStatus();

            } else {

                return null;

            }

        }


        return $this->_identity;

    }




// ...




    /**

 	* Updates the authentication status using the information from session and cookie.

 	*

 	* This method will try to determine the user identity using the [[idParam]] session variable.

 	*

 	* If [[authTimeout]] is set, this method will refresh the timer.

 	*

 	* If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]

 	* if [[enableAutoLogin]] is true.

 	*/

    protected function renewAuthStatus()

    {

        $session = Yii::$app->getSession();

        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;


        if ($id === null) {

            $identity = null;

        } else {

            /* @var $class IdentityInterface */

            $class = $this->identityClass;

            $identity = $class::findIdentity($id);

        }


        $this->setIdentity($identity);


        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {

            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;

            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;

            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {

                $this->logout(false);

            } elseif ($this->authTimeout !== null) {

                $session->set($this->authTimeoutParam, time() + $this->authTimeout);

            }

        }


        if ($this->enableAutoLogin) {

            if ($this->getIsGuest()) {

                $this->loginByCookie();

            } elseif ($this->autoRenewCookie) {

                $this->renewIdentityCookie();

            }

        }

    }




Thank you! That helped me to track down the problem. I am using modules and the app was configured to use the wrong User model.

Nice! You are welcome.