Geoff
Geoff

Reputation: 6639

Yii2 expiring access tokens

Am implementing a restful api with yii2 and i would like to know how to expire a user's access token

In my login controller

if($model->login()){
      return [
        "access_token' => Yii::$app->user->identity->getAuthKey(),
        ];
  }

Now in my other controllers am implementing this behaviour

class DefaultController extends Controller {

    $behaviors['authenticator']           = [
        'class'       => CompositeAuth::className(),
        'authMethods' => [
            QueryParamAuth::className(),
        ],
    ];

  }

Which works whenever iu send my request with access-token in my url

But now the problem is that the access token doesnt expire

How do i set the expiry time of the access token?

Upvotes: 0

Views: 3933

Answers (1)

karpy47
karpy47

Reputation: 900

In your User model add an attribute 'access_token' and change/add something like this...

public static function findIdentityByAccessToken($token, $type = NULL)
{
    // find user with token
    if ($user = static::findOne(['access_token' => $token])) {
        return $user->isAccessTokenValid() ? $user : null;
    }
    return null;
}

public function generateAccessToken($expireInSeconds)
{
    $this->access_token = Yii::$app->security->generateRandomString() . '_' . (time() + $expireInSeconds);
}

public function isAccessTokenValid()
{
    if (!empty($this->access_token)) {
        $timestamp = (int) substr($this->access_token, strrpos($this->access_token, '_') + 1);
        return $timestamp > time();
    }
    return false;
}

Obviously you need to call generateAccessToken() to set a valid access token.

Note! Code is not tested.

Upvotes: 5

Related Questions