How to set up and configure Laravel Passport for OAuth2 server functionality



Image not found!!

Setting up and configuring Laravel Passport for OAuth2 server functionality involves a few steps. Laravel Passport is an OAuth2 server that provides a full implementation of the OAuth2 server specification. Here's a step-by-step guide along with an example:

Step 1: Install Laravel Passport

First, install Laravel Passport using Composer:

bash
composer require laravel/passport


Step 2: Run Passport Install Command

Run the Passport install command to set up the necessary database tables and migrations:

bash
php artisan passport:install


Step 3: Set up User Model

In your User model (typically located at app/Models/User.php), use the Laravel\Passport\HasApiTokens trait:

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


Step 4: Update AuthServiceProvider

In the AuthServiceProvider (typically located at app/Providers/AuthServiceProvider.php), import Passport and register the necessary routes:

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


Step 5: Update config/auth.php

In your config/auth.php file, ensure that the API guard uses the Passport driver:

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


Step 6: Update Kernel

In the app/Http/Kernel.php file, include the \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class middleware in the web group:

php
protected $middlewareGroups = [ 'web' => [ // ... \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], // ... ];


Step 7: Run Migrations

Run the database migrations to apply the changes:

bash
php artisan migrate


Step 8: Configure OAuth Clients

To create an OAuth client, use the passport:client Artisan command. This command will prompt you for the necessary information:

bash
php artisan passport:client


Example Usage

Once configured, you can use Passport to protect routes and authenticate users. Here's a simple example of protecting an API route:

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


Research Links

Make sure to consult the Laravel Passport documentation for any updates or changes in the configuration process.



=== Happy Coding :)