yii2yii2-api

Yii2 Rest Api User bearer Authentication expiration time


i am currently working on a yii2 based Rest api. i use bearer token for user authentication.let me explain the requirement.

1)first user authenticated from a external php application using their credentials.

2)he/she got an access Token.

3)each subsequent request is made using this access token.

public static function findIdentityByAccessToken($token, $type = null)
{
    return static::findOne(['auth_key' => $token]);
}

this is where i start thinking. i do not found any expiration time for the access token. is that really needed? if yes how can i archive that? Thanks in advance.


Solution

  • Your question is kind of broad, but I will attempt to help your thought process along.

    i do not found any expiration time for the access token. is that really needed?

    That depends on your requirements. Do you want your users to be able to access your API indefinitely after authenticating the first time? Would you like your users to renew their token every so often?

    I would recommend the latter, as it limits the time a potential attacker could use a compromised access token.

    if yes how can i archive that?

    One option would be to add a field containing the datetime of the expiry date to the database table corresponding with your identity class and to check wether this is still valid in the implementation of findIdentityByAccessToken()

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne([
            'AND', 
            ['auth_key' => $token], 
            ['>=', 'token_expire', new \yii\db\Expression('NOW()')]
        ]);
    }