How to set up and use Laravel Passport for implementing secure API authentication



Image not found!!

Laravel Passport is a full OAuth2 server implementation for Laravel. It allows you to easily set up and use OAuth2 for secure API authentication. Here's a step-by-step guide on how to set up Laravel Passport with an example:

Step 1: Install Laravel Passport

Run the following command to install Passport via Composer:

bash
composer require laravel/passport

Step 2: Run Migrations

Run the migrations to create the necessary tables for Passport:

bash
php artisan migrate

Step 3: Install Passport

Install Passport using the following Artisan command:

bash
php artisan passport:install

This command creates the encryption keys needed to generate secure access tokens.

Step 4: Configure Passport

In your AuthServiceProvider located at app/Providers/AuthServiceProvider.php, make sure to call Passport::routes() within the boot method:

php
use Laravel\Passport\Passport; public function boot() { $this->registerPolicies(); Passport::routes(); }

Step 5: Set up your User model

In your User model, use the Laravel\Passport\HasApiTokens trait:

php
use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // ... }

Step 6: Update Auth Configuration

In your config/auth.php file, make sure the api guard uses the passport driver:

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

Step 7: Create a Passport Client

Run the following command to create a client:

bash
php artisan passport:client

This command will prompt you to choose the type of client (e.g., "Password grant client"). You can choose according to your needs.

Step 8: API Routes

Protect your API routes using the auth:api middleware. For example:

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

Step 9: Requesting Tokens

You can use tools like Postman or cURL to request access tokens. For password grant, you'll need to send a POST request to /oauth/token with the client credentials and user credentials.

Additional Links:

  1. 1. Laravel Passport Documentation: https://laravel.com/docs/passport
  2. 2. Laravel API Authentication with Passport: https://laravel.com/docs/authentication
  3. 3. Laravel Passport on GitHub: https://github.com/laravel/passport

These resources will provide more in-depth information on using Laravel Passport and handling various authentication scenarios.



=== Happy Coding :)