How to use Passport Token in Laravel

AuthorSumit Dey Sarkar

Pubish Date19 Mar 2023

categoryLaravel

In this tutorial we will learn how to use passport tolen in laravel.

In Laravel, you can use Passport to issue API tokens that can be used to authenticate API requests. Here's how you can use Passport to issue and authenticate tokens:

 

How to use passport token in laravel

To use password token in Laravel, you can follow these steps:

 

1) Install and configure Passport:

  • Install Passport using Composer: `composer require laravel/passport`
  • Run the Passport installation command: `php artisan passport:install`
  • Add the `Laravel\Passport\HasApiTokens` trait to your User model.

 

2) Create a route to issue a token:

  • Add the `CreateFreshApiToken` middleware to your web middleware group in `app/Http/Kernel.php`.
  • Create a route to issue a token using the `auth:api` middleware, e.g. `Route::middleware('auth:api')->get('/user', function () { return Auth::user(); });`

 

3) Authenticate API requests with a token:

  • Send a `POST` request to `/oauth/token` with the following parameters: `grant_type=password`, `client_id`, `client_secret`, `username`, and `password`. This will return an access token that can be used to authenticate subsequent requests.
  • Include the access token in the `Authorization` header of API requests, e.g. `Authorization: Bearer {access_token}`.

 

Here's an example of how to issue a token and use it to authenticate a request in Laravel:

// Issue a token
$response = $client->post('/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => '{client_id}',
        'client_secret' => '{client_secret}',
        'username' => '{username}',
        'password' => '{password}',
    ],
]);
$token = json_decode((string) $response->getBody(), true)['access_token'];

// Use the token to authenticate a request
$response = $client->get('/api/user', [
    'headers' => [
        'Authorization' => 'Bearer '.$token,
        'Accept' => 'application/json',
    ],
]);
$user = json_decode((string) $response->getBody(), true);
Comments 0

Leave a comment