How to configure and use the Laravel Passport package for OAuth2 authentication



Image not found!!

Laravel Passport is a package that provides a full OAuth2 server implementation for your Laravel application. It makes it easy to set up OAuth2 authentication in your Laravel API. Below are the steps to configure and use Laravel Passport for OAuth2 authentication:

Step 1: Install Passport

To install Passport, run the following Composer command:

bash
composer require laravel/passport

Step 2: Set up the Database

Run the migration command to create the necessary tables for Passport:

bash
php artisan migrate

Step 3: Install Passport

Next, install Passport using the passport:install Artisan command. This command will create the encryption keys needed to generate secure access tokens:

bash
php artisan passport:install

Step 4: Configure AuthServiceProvider

In your AuthServiceProvider (located at app/Providers/AuthServiceProvider.php), add the following lines to the boot method:

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

Step 5: Update User Model

In your User model (usually located at app/User.php), implement the HasApiTokens trait:

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

Step 6: Update auth configuration

In your config/auth.php file, make sure the api driver is set to passport:

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

Step 7: Run your application

After completing the setup, run your Laravel application:

bash
php artisan serve

Step 8: Create API Routes

Now, you can define routes for handling OAuth2 authentication. Typically, this involves creating routes for login, registration, and accessing protected resources.

Step 9: Requesting Access Tokens

To obtain an access token, you need to send a POST request to the /oauth/token endpoint with the client credentials and user credentials.

Step 10: Protecting Routes

Use Passport's auth:api middleware to protect routes that require authentication. Apply the middleware to your API routes:

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

That's it! You've now set up Laravel Passport for OAuth2 authentication in your Laravel application. Make sure to refer to the official Laravel Passport documentation for more detailed information and advanced configurations: Laravel Passport Documentation.




=== Happy Coding :)