Skip to content

Instantly share code, notes, and snippets.

@salipro4ever
Created October 3, 2018 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save salipro4ever/ebe4730db5efbced25d713aa145294d6 to your computer and use it in GitHub Desktop.
Save salipro4ever/ebe4730db5efbced25d713aa145294d6 to your computer and use it in GitHub Desktop.
Get client from Client Credentials Grant - Laravel Passport
    $bearerToken=$request->bearerToken();
    $tokenId= (new \Lcobucci\JWT\Parser())->parse($bearerToken)->getHeader('jti');
    $client = \Laravel\Passport\Token::find($tokenId)->client;

OR

Update your app/Http/Kernel.php to use your custom middleware instead of the build in Passport middleware:

protected $routeMiddleware = [
    'client' => \App\Http\Middleware\MyCheckClientCredentials::class,
];

Apply the middleware to your route as normal:

Route::get('/user', function(Request $request) {
    // Should show "oauth_client_id" field.
    dd($request->all());
})->middleware('client');
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\AuthenticationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Laravel\Passport\Http\Middleware\CheckClientCredentials;
class MyCheckClientCredentials extends CheckClientCredentials
{
/**
* The Resource Server instance.
*
* @var \League\OAuth2\Server\ResourceServer
*/
private $server;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$scopes
* @return mixed
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$scopes)
{
$psr = (new DiactorosFactory)->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
// This is the custom line. Set an "oauth_client_id" field on the
// request with the client id determined by the bearer token.
$request['oauth_client_id'] = $psr->getAttribute('oauth_client_id');
} catch (OAuthServerException $e) {
throw new AuthenticationException;
}
$this->validateScopes($psr, $scopes);
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment