yii\web\User::loginByAccessToken PHP Method

loginByAccessToken() public method

This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]] with the provided access token. If successful, it will call User::login to log in the authenticated user. If authentication fails or User::login is unsuccessful, it will return null.
public loginByAccessToken ( string $token, mixed $type = null ) : yii\web\IdentityInterface | null
$token string the access token
$type mixed the type of the token. The value of this parameter depends on the implementation. For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
return yii\web\IdentityInterface | null the identity associated with the given access token. Null is returned if the access token is invalid or [[login()]] is unsuccessful.
    public function loginByAccessToken($token, $type = null)
    {
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentityByAccessToken($token, $type);
        if ($identity && $this->login($identity)) {
            return $identity;
        } else {
            return null;
        }
    }

Usage Example

Example #1
0
 /**
  * Authenticates the current user.
  *
  * @param \yii\web\User     $user
  * @param \yii\web\Request  $request
  * @param \yii\web\Response $response
  *
  * @return \yii\web\IdentityInterface the authenticated user identity. If authentication information is not
  *                                    provided, null will be returned.
  * @throws \yii\web\UnauthorizedHttpException if authentication information is provided but is invalid.
  */
 public function authenticate($user, $request, $response)
 {
     /** @var array $request */
     /** @noinspection PhpUndefinedFieldInspection */
     $request = Json::decode($request->rawBody);
     $token = ArrayHelper::getValue($request, $this->accessTokenPath);
     if (!$token || !($identity = $user->loginByAccessToken($token))) {
         \Yii::$app->session->remove(TokenAuth::DEFAULT_TOKEN_PATH);
         throw new UnauthorizedHttpException('Incorrect or expired token provided');
     }
     \Yii::$app->session->set(TokenAuth::DEFAULT_TOKEN_PATH, $token);
     return $identity;
 }