Yii2 how to improve JWT caching? - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, June 4, 2021

Yii2 how to improve JWT caching?

Trying to authenticate against a third party, I want to cache my returned JWT as long and robust as possible. (the expiration might change for example)

I wanted to use the getOrSet function of Yii::$app->cache in a more elaborate manner, but it is not possible to set the duration dynamically depending on the token expiry when handling everything within the callable part.

Am I missing anything in the Yii2 cache function here? Or is there a better library to cache my tokens that also supports passing a callable that retrieves the token?

My current code sample:

function getAccesToken($url)
{
    $cacheKey = 'login-token-' . $url;
    $token = Yii::$app->cache->get($cacheKey);
    // check if token is still valid (!== null) 
    // and is not expired using the loadToken function of bizley/jwt 
    // which returns null if token can not be validated
    // if valid a Lcobucci\JWT\Token is returned
    if ($token !== false && (new bizley\jwt\Jwt())->loadToken($token, true, false) !== null) {
        return $token;
    }
    $token = getTheJwtFromHttpEndpoint();
    // check if returned token is valid
    // returns a Lcobucci\JWT\Token if valid, null otherwise
    $token = (new bizley\jwt\Jwt())->loadToken($response, true, false); 
    if ($token === null) { 
        throw new \Exception('Invalid token received');
    }
    
    return Yii::$app->cache->getOrSet(
        $cacheKey,
        fn () => $token->toString(),
        // set the cache duration oriented by the expiration claim and a one minute leeway
        $token->claims()->get('exp')->getTimestamp() - (new \DateTime())->getTimestamp() - 60
    );
}


source https://stackoverflow.com/questions/67826839/yii2-how-to-improve-jwt-caching

No comments:

Post a Comment