How to use Laravel Passport for implementing API authentication with personal access tokens



Image not found!!

Laravel Passport is a popular OAuth2 server for Laravel applications, which makes it easy to implement API authentication. It provides support for various grant types, including personal access tokens. Below is a step-by-step guide on how to use Laravel Passport for API authentication with personal access tokens:

Step 1: Install Passport

Install Laravel Passport using Composer:

bash
composer require laravel/passport

Step 2: Run Migrations

Run the Passport migrations to create the necessary database tables:

bash
php artisan migrate

Step 3: Install Passport

Install Passport using the install Artisan command:

bash
php artisan passport:install

This command will generate encryption keys and create the necessary database tables for Passport.

Step 4: Configure the User Model

Make your User model implement the HasApiTokens trait:

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

Step 5: Set Up the AuthServiceProvider

In your AuthServiceProvider, add the following lines to the boot method:

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

Step 6: Create API Routes

In your routes/api.php file, define the routes that should be protected by Passport:

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

Step 7: Create Personal Access Token

To create a personal access token, you can use the createToken method on a user instance:

php
$user = User::find(1); $token = $user->createToken('Token Name')->accessToken;