Laravel Passport: How do i get Access token from Bearer Token

To get the user by the token, you need to understand what the token is.

The token is broken up into three base64 encoded parts: the header, the payload, and the signature, separated by periods. In your case, since you're just wanting to find the user, you just need the header

To get the header, you can do something like this:

$access_token = "eyJ0eXAiOiJKV1QiLCJhbGcXXXJSUzI......"

// break up the string to extract only the token

$auth_header = explode(' ', $access_token);
$token = $auth_header[1];

// break up the token into its three respective parts
$token_parts = explode('.', $token);
$token_header = $token_parts[0];

// base64 decode to get a json string
$token_header_json = base64_decode($token_header);
// you'll get this with the provided token:



{"typ":"JWT","alg":"RS256","jti":"9fdb0dc4382f2833ce2d3993c670fafb5a7e7b88ada85f490abb90ac211802720a0fc7392c3f2e7c"}

// then convert the json to an array
$token_header_array = json_decode($token_header_json, true);

Once you have this, you can find the user's token in the jti key:

$user_token = $token_header_array['jti'];

I learnt this from @samsquanch


*if you guys got any better solution let me know...

so far, this is how i kill it:

  1. I Overriding CheckClientCredentials middleware:

    use Laravel\Passport\Http\Middleware\CheckClientCredentials as Middleware;
    
    class CheckClientCredentials extends Middleware{
    
    public function handle($request, Closure $next, ...$scopes){
        $psr = (new DiactorosFactory)->createRequest($request);
    
        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);
        } catch (OAuthServerException $e) {
            throw new AuthenticationException;
        }
    
        $this->validateScopes($psr, $scopes);
    
        $request->attributes->set('oauth_access_token_id', $psr->getAttribute('oauth_access_token_id'));
        $request->attributes->set('oauth_client_id', $psr->getAttribute('oauth_client_id'));
        $request->attributes->set('oauth_user_id', $psr->getAttribute('oauth_user_id'));
        $request->attributes->set('oauth_scopes', $psr->getAttribute('oauth_scopes'));
    
        return $next($request);
    }
    

    }

  2. access it in controller:

    dd($request->get('oauth_access_token_id'));