Sunday, 16 April 2023

Laravel passport api integration step by step

Here are the steps to integrate Laravel Passport API authentication into your Laravel application:

  1. Install Laravel Passport package:

    bash
    composer require laravel/passport
  2. Run migration to create the necessary tables for Passport:

    php artisan migrate
  3. Add the Passport service provider to the config/app.php file:

    arduino
    'providers' => [ // ... Laravel\Passport\PassportServiceProvider::class, ]
  4. In your AppServiceProvider, add the following to the boot() method to configure Passport:

    php
    use Laravel\Passport\Passport; public function boot() Passport::routes(); }
  5. Run the Passport installation command to generate encryption keys:

    php artisan passport:install
  6. Add the Laravel\Passport\HasApiTokens trait to your User model:

    php
    use Laravel\Passport\HasApiTokens; class User extends Authenticatable {use HasApiTokens, Notifiable; // }
  7. In your config/auth.php file, add the api guard and set the driver to passport:

    arduino
    'guards' => [ // ... 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ]
  8. In your routes/api.php file, define the routes that require authentication using the auth:api middleware:

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

That's it! Now you can use the /oauth/token endpoint to generate access tokens for your API clients. You can also use the Passport middleware to protect other routes that require authentication.

No comments:

Post a Comment

Other post

1) The create() Method The  create()  method is a powerful and convenient way to store data in your Laravel application. It is typically use...