Home > Software design >  how to pass token as header authuriazation token in laravel
how to pass token as header authuriazation token in laravel

Time:12-21

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

CodePudding user response:

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);
}

CodePudding user response:

You can access it by calling the request->session->token

public function getalluser(User $user)
{
    $user = User::where('id', $user)->first(); // this is rather redundant since you are doing model data binding 
    return response()->json([
            'user' => $user,
            'thtoken' => request()->session()->token(),
    ]);
}
  • Related