vivek kn
vivek kn

Reputation: 265

how to pass token as header authuriazation token in laravel

I am trying to create a get API. I am using Larvel passport for generating token

I want to pass generated token as header for the API. How can I do that?

public function getalluser(User $user)
{
  
   
 $user = User::where('id', $user)->first();
 return response()->json([
            'user' => $user,
 ]);    
}
}

enter image description here

Here even with out passing the authorization token I am getting some response if there is no token passed I want error and I want to pass token in order for this API to work

enter image description here

enter image description here

Upvotes: 0

Views: 642

Answers (1)

Dmitry K.
Dmitry K.

Reputation: 3198

As I understand your question - you want to get an authenticated user by token.

Follow installation instructions from Laravel docs - https://laravel.com/docs/9.x/passport#installation
Especially this part:

Finally, in your application's config/auth.php configuration file, you should define an api authentication guard and set the driver option to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
 
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
], 

To authenticate users you should use the api guard.

Now you can create route to get current authenticated user - https://laravel.com/docs/9.x/passport#via-middleware

Route::get('/user', function (\Illuminate\Http\Request $request) {
    // You will get authenticated user here
    $user = $request->user();
    dump($user);

    return new \Illuminate\Http\JsonResponse(['id' => $user->id], 200);
})->middleware('auth:api');

And here is about how pass authentication token to your app - https://laravel.com/docs/9.x/passport#passing-the-access-token
Just add Authorization header with this value Bearer: <PUT_HERE_YOUR_TOKEN>, replace <PUT_HERE_YOUR_TOKEN> with your issued token.

UPD: If you want to get token used to authenticate user, you can look at Passport middleware source code - https://github.com/laravel/passport/blob/11.x/src/Guards/TokenGuard.php

if ($this->request->bearerToken()) {
    return $this->user = $this->authenticateViaBearerToken($this->request);
} elseif ($this->request->cookie(Passport::cookie())) {
    return $this->user = $this->authenticateViaCookie($this->request);
}

Upvotes: 1

Related Questions