How to convert token_id of passport to access_token by laravel

  1. event of creating tokens through passport AccessTokenCreated how is the generated token, converted to the corresponding access_token based on the generated token_id in this event?
Aug.22,2021

look for the source code and rewrite it according to his format, which is not very elegant

<?php

namespace App\Listeners;

use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Laravel\Passport\Bridge\AccessToken;
use Laravel\Passport\Bridge\AccessTokenRepository;
use Laravel\Passport\Bridge\AuthCodeRepository;
use Laravel\Passport\Bridge\ClientRepository;
use Laravel\Passport\Bridge\Scope;
use Laravel\Passport\Events\AccessTokenCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Laravel\Passport\Passport;
use Laravel\Passport\Token;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Entities\Traits\AccessTokenTrait;
use League\OAuth2\Server\Entities\Traits\EntityTrait;
use League\OAuth2\Server\Entities\Traits\TokenEntityTrait;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
use League\OAuth2\Server\Grant\AbstractGrant;

class RevokeOldTokens
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AccessTokenCreated  $event
     * @return void
     */
    public function handle(AccessTokenCreated $event)
    {
        $provider = Config::get('auth.guards.api.provider');
        $key2 = $event->clientId . '-sharp' . $event->userId . '-sharp' . $provider;
        $key1 = md5((string)$this->tokenIdConvertBearer($event->userId, $event->tokenId, $event->clientId));
        Redis::hdel(Redis::hget($key2, 'token'), 'provider', 'uid', 'cid'); // token

        Redis::pipeline(function ($pipe) use ($event, $provider, $key1, $key2) {
            $time = Carbon::now()->add(Passport::tokensExpireIn())->timestamp;
            $pipe->hset($key1, 'cid', $event->clientId);
            $pipe->hset($key1, 'uid', $event->userId);
            $pipe->hset($key1, 'provider', $provider);
            $pipe->expireat($key1, $time);
            $pipe->hset($key2, 'token', $key1);
            $pipe->expireat($key2, $time);
        });

        // token
        Token::where('id', '!=', $event->tokenId)
            ->where('user_id', $event->userId)
            ->where('client_id', $event->clientId)
            ->where('expires_at', '<', Carbon::now())
            ->orWhere('revoked', true)
            ->delete();
    }

    private function tokenIdConvertBearer($userId, $tokenId, $clientId){
        $privateKey = new CryptKey(
            'file://'.Passport::keyPath('oauth-private.key'),
            null,
            false
        );

        $request = app()->get('request');
        $scopes = $this->getScopesEntityByIdentifiers($request->input('scope'));
        $accessToken = (new AccessToken($userId, $scopes));
        $clientRepository = app()->make(ClientRepository::class);
        $client = $clientRepository->getClientEntity(
            $clientId,
            $request->input('grant'),
            $request->input('client_secret'),
            true
            );
        $accessToken->setClient($client);
        $accessToken->setUserIdentifier($userId);
        $accessToken->setExpiryDateTime((new \DateTime())->add(Passport::tokensExpireIn()));
        $maxGenerationAttempts = AbstractGrant::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
        while ($maxGenerationAttempts-- > 0) {
            $accessToken->setIdentifier($tokenId);
        }

        return $accessToken->convertToJWT($privateKey);
    }

    private function getScopesEntityByIdentifiers($scopes) {
        $scopesList = array_filter(explode(' ', trim($scopes)), function ($scope) {
            return !empty($scope);
        });

        $validScopes = [];

        foreach ($scopesList as $scopeItem) {
            $scope = new Scope($scopeItem);

            if ($scope instanceof ScopeEntityInterface === false) {
                throw OAuthServerException::invalidScope($scopeItem);
            }

            $validScopes[] = $scope;
        }

        return $validScopes;
    }
}
Menu