adam78
adam78

Reputation: 10078

Laravel Passport Get Client ID from Bearer Token

I've set up the laravel passport and created clients. When clients make a post request to my application using it api, all they send is the bearer access token along with the post values.

Is there any way I can get the client id of the consuming application when they submit the post request simply from the bearer token.

Or is it entirely safe for the consuming application to send their client id along with the post fields?

Upvotes: 2

Views: 3129

Answers (4)

TheLegendaryCopyCoder
TheLegendaryCopyCoder

Reputation: 1842

This is what finally worked for me with Laravel 8.

Note that I plagerised the solution from @judge2020's answer on GitHub.

use Laravel\Passport\Token;
use Lcobucci\JWT\Configuration; /* composer require lcobucci/jwt */

Route::get('/v1/test', function(Request $request) {   

    $bearerToken = request()->bearerToken();
    $tokenId = Configuration::forUnsecuredSigner()->parser()->parse($bearerToken)->claims()->get('jti');
    $client = Token::find($tokenId)->client;
    
})->middleware('client');

Upvotes: 1

Dan
Dan

Reputation: 3584

If you deal with the grant type client_credentials you might consider the following solution:

Route::get('/get-client-cred', function (Request $request) {
    $bearerToken = $request->bearerToken();

    $tokenId = (new \Lcobucci\JWT\Parser())->parse($bearerToken)->getHeader('jti');

    return \Laravel\Passport\Token::find($tokenId)->client;
})->middleware('client_credentials');

Instead, if you are dealing with a personal access token you can retrieve the client as following:

Route::middleware('auth:api')->get('/get-client', function (Request $request) {
    return $request->user()->token()->client;
});

Upvotes: 2

adam78
adam78

Reputation: 10078

I think this is what i need:

$request->user()->token()->client

Upvotes: 4

Rouhollah Mazarei
Rouhollah Mazarei

Reputation: 4153

If you have used passport you can get the user id from the Auth facade using api guard like this:

$user_id = Auth::guard('api')->id();

or get the user:

$user = Auth::guard('api')->user();

Upvotes: 0

Related Questions