Laravel Passport get user Access Token after being issued

I’m using Laravel Passport to issue Bearers to the user once it’s logged in and then be able to connect to the API (yes I know Sanctum might fit better my needs but I’m using Passport so don’t even mention to switch to Sanctum), then on the Front-end, I store the user email and the Bearer in a cookie to use them later on for other queries and add the bearer to Axios Auth header though now I have a problem with my logic, maybe related to the fact that I don’t know how to use Passport correctly in Nuxt.

I have queries for each page where I send the user email in a post request and they return back a mix of global info and user info.

Yes, my endpoints are already behind an auth middleware but I just send a Bearer Token to allow the endpoint to be queried with any data, there is no prevention to ask for User B info from User A.

How can I use prevent the user to send a different email and get another user’s info?

This is how I issue an access token:

$token    = $user->createToken('Laravel Password Grant Client')->accessToken;

there is a way to do something like this?

$user = User::where('email', $request->email)->first();
// E.g. [email protected]  ...

// Get the user Access Token
$userToken    = $user->getAccessToken;
// E.g. someBerareText

// check if the User Access Token match with the one send in the request
// if they don't match throw a 401
if ($userToken !== $request->header('Authorization')) {
   return response()->json([ "error" => "Not Authorized" ], 401);
...

// E.g. $request->header('Authorization') it's SomeOtherBearer because he
// requested info for [email protected] but the $request->header('Authorization')
// belong to [email protected]

The user can still send the same request but with User B’s email and see other info that doesn’t belong to him, so how can I check if the email in the $request belongs to the user that’s actually logged in?

some way to decode the access token and check if it really belongs to the user or not?

Answer

If Laravel Passport is set up as the guard, it will fetch the user from the bearer token, the logic can be seen in the TokenGuard.php class in Passport. It actually does the same as you want to achieve.

So the authentication works different compared to the guard used. Therefor Passport requires you to change the guard. This is the deciding factor how Laravel differentiate Authentication and for that matter how the Auth::user() is loaded.

'guards' => [
    ...

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

This means that you can check if the user is the correct authenticated with the model function is() that compare if the models are the same.

User::where('email', $request->email)->first()->is(Auth::user())

Leave a Reply

Your email address will not be published. Required fields are marked *