For my situation, I need to get client id from per request and record it into the database, but how to get it from a request in Laravel passport? There are many ways to do it.


It’s a claim in JWT(RFC), just following to do

$client_id = (new Parser())->parse($request->bearerToken())->getClaim('aud');
$request->request->set('client_id', $client_id);

It’s good, but there are some problems with it

  1. It’s optional in JWT.
  2. You need to get it in middleware you making or controller.

jti(JWT ID)

As upon above, you can get it from jti, and validate it in the model.

$token_id = (new Parser())->parse($request->bearerToken())->getClaim('jti');
$client = Token::find($token_id)->client;
$client_id = $client->id;

The problems are the same as above, optional, and we got another problem, more query to the database.

Check client Credential

I think it the best way I’m knowing for now, overwrite Laravel\Passport\Http\Middleware\CheckClientCredentials , when the request is coming, set the client_id and passing next.


namespace App\Http\Middleware;

use Illuminate\Auth\AuthenticationException;
use Laravel\Passport\TokenRepository;
use Laravel\Passport\Http\Middleware\CheckClientCredentials as PassportClientCredentials;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\ResourceServer;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Zend\Diactoros\ResponseFactory;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\StreamFactory;
use Zend\Diactoros\UploadedFileFactory;
use Closure;

class CheckClientCredentials extends PassportClientCredentials
    public function __construct(ResourceServer $server, TokenRepository $repository)
        parent::__construct($server, $repository);

     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param mixed …$scopes
     * @return mixed
     * @throws AuthenticationException
     * @throws \Laravel\Passport\Exceptions\MissingScopeException
    public function handle($request, Closure $next, ...$scopes)
        $psr = (new PsrHttpFactory(
            new ServerRequestFactory,
            new StreamFactory,
            new UploadedFileFactory,
            new ResponseFactory

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);
            $request->request->set('client_id', $psr->getAttribute('oauth_client_id'));
        } catch (OAuthServerException $e) {
            throw new AuthenticationException;

        $this->validate($psr, $scopes);

        return $next($request);

The PSR includes ServerRequest:

ServerRequest {
    attributes: {
        "oauth_access_token_id" => "xxxxx"
        "oauth_client_id" => "1"
        "oauth_user_id" => ""
        "oauth_scopes" => [

Next, Changing Kernel.php using instance, For per request, you can get client_id $request->get('client_id');

php – Laravel Passport Get Client ID By Access Token – Stack Overflow