How to Use Laravel Passport For API Authentication?

12 minutes read

Laravel Passport is a package that provides a simple and convenient way to implement API authentication in your Laravel application. It leverages the OAuth2 protocol to provide a secure token-based authentication system.


To use Laravel Passport for API authentication, you need to follow these steps:

  1. Install Laravel Passport: Use Composer to install Laravel Passport by running the following command in your terminal: composer require laravel/passport
  2. Set up the Passport service provider: Open your config/app.php file and add the following line to the 'providers' array: Laravel\Passport\PassportServiceProvider::class
  3. Run the Passport migrations: Laravel Passport requires a few tables to be set up in your database. Run the migrations using the following command: php artisan migrate
  4. Create the encryption keys: Generate the encryption keys required to generate secure access tokens by running the following command: php artisan passport:keys
  5. Set up the authentication routes: Open your app/Providers/AuthServiceProvider.php file and add the following lines to the boot() method: use Laravel\Passport\Passport; Passport::routes();
  6. Prepare the User model: In your App\User model, import the Laravel\Passport\HasApiTokens trait and add it to the class, as shown below: use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens; // ... }
  7. Configure the Passport settings: Open your config/auth.php file and update the guards and providers arrays to use Passport implementations for API authentication.
  8. Generate the encryption keys: Run the following command to generate the encryption keys required for Passport: php artisan passport:install
  9. Use Passport in your routes or controllers: You can now authenticate API requests using the auth:api middleware provided by Passport. This middleware will verify the access token present in the request headers. Example usage in a route: Route::get('/user/profile', function () { // Only authenticated requests with valid access tokens will be able to access this route. })->middleware('auth:api');


By following these steps, you can use Laravel Passport to authenticate API requests in your Laravel application.

Best Laravel Frameworks Books to Read in 2024

1
Laravel: Up and Running: A Framework for Building Modern PHP Apps

Rating is 5 out of 5

Laravel: Up and Running: A Framework for Building Modern PHP Apps

2
Beginning Laravel: Build Websites with Laravel 5.8

Rating is 4.9 out of 5

Beginning Laravel: Build Websites with Laravel 5.8

3
Laravel: Up & Running: A Framework for Building Modern PHP Apps

Rating is 4.8 out of 5

Laravel: Up & Running: A Framework for Building Modern PHP Apps

4
Laravel: Up & Running

Rating is 4.7 out of 5

Laravel: Up & Running

5
Practical Laravel: Develop clean MVC web applications

Rating is 4.6 out of 5

Practical Laravel: Develop clean MVC web applications

6
Laravel - Un framework efficace pour développer vos applications PHP

Rating is 4.5 out of 5

Laravel - Un framework efficace pour développer vos applications PHP


How to create OAuth clients using Laravel Passport?

To create OAuth clients using Laravel Passport, you can follow these steps:

  1. Install Laravel Passport by running the following command in your terminal:
1
composer require laravel/passport


  1. After the installation is complete, run the following command to migrate the necessary database tables:
1
php artisan migrate


  1. Next, run the Passport installation command to generate the encryption keys used to generate secure access tokens:
1
php artisan passport:install


  1. Once the installation is complete, you can add the Laravel\Passport\HasApiTokens trait to your User model.
  2. In your AuthServiceProvider class, add the Passport routes to your boot method:
1
2
3
4
5
6
7
8
use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();

    Passport::routes();
}


  1. After adding the Passport routes, run the following command to generate the encryption keys for clients:
1
php artisan passport:client --password


This command will generate a client ID and client secret for you. Make sure to store these keys securely.

  1. You can also create other types of clients by using different command options. For example, to create "personal access" clients, run the command:
1
php artisan passport:client --personal


  1. Once you have the client ID and secret, you can use them in your OAuth client. For example, if you are creating a mobile app as a client, you can use these credentials to authenticate and obtain access tokens.


These are the basic steps to create OAuth clients using Laravel Passport. However, you may need to modify the configuration and settings based on your application's requirements.


How to log API requests and responses using Laravel Passport?

To log API requests and responses using Laravel Passport, you can follow these steps:


Step 1: Install Laravel Passport

  • Install Laravel Passport using the Composer package manager by running the following command in your terminal:
1
composer require laravel/passport


Step 2: Set up Passport

  • Run the migration command to set up the necessary tables for Passport:
1
php artisan migrate


  • Next, run the command to install the Passport routes:
1
php artisan passport:install


  • Generate encryption keys for Passport using the following command:
1
php artisan passport:keys


Step 3: Create a custom middleware

  • Create a new middleware that will log the requests and responses. Run the following command to generate a new middleware class:
1
php artisan make:middleware LogRequestResponse


  • Open the generated LogRequestResponse middleware file and replace the handle method with the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public function handle($request, Closure $next)
{
    $response = $next($request);

    // Log the request and response
    Log::info('Request', ['request' => $request->all()]);
    Log::info('Response', ['response' => $response->getContent()]);

    return $response;
}


Step 4: Register the middleware

  • Open the App\Http\Kernel class and add the following line to the protected $middleware array:
1
2
3
4
protected $middleware = [
    // ... other middleware
    \App\Http\Middleware\LogRequestResponse::class,
];


Step 5: Capture the request and response

  • To capture the request and response, you can use Laravel's built-in logging mechanism. In your controller or wherever you want to log the request and response, add the following code:
1
2
3
Log::info('Request', ['request' => $request->all()]);
// Your API logic here
Log::info('Response', ['response' => $response->getContent()]);


That's it! Laravel Passport will now log the API requests and responses using the defined middleware and logging mechanism. You can find the logs in the storage/logs directory.


How to configure Laravel Passport for multiple authentication guards?

To configure Laravel Passport for multiple authentication guards, you would need to follow these steps:

  1. Install Laravel Passport by running the following command in your terminal:
1
composer require laravel/passport


  1. Once installed, you need to run the migration command to create the necessary tables for Passport:
1
php artisan migrate


  1. Next, you need to run the Passport installation command to generate the encryption keys and other necessary files:
1
php artisan passport:install


  1. In the config/auth.php file, define multiple authentication guards by adding new guard configurations. For example, if you want to add a guard called "api-user", you can add the following code within the guards array:
1
2
3
4
'api-user' => [
    'driver' => 'passport',
    'provider' => 'users',
],


Make sure the driver is set to 'passport' and the provider is set to the correct user provider for this guard.

  1. Configure your User model by implementing the Laravel\Passport\HasApiTokens trait. This trait will add the necessary methods to generate the access tokens for the users.
1
2
3
4
5
6
7
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    ...
}


  1. In your AuthServiceProvider (typically located in app/Providers/AuthServiceProvider.php), you need to override the boot method to define the passport guards for each authentication guard. For example, to configure the "api-user" guard, update the boot method as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use Laravel\Passport\Passport;

public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);

    Passport::setDefaultScope([
        'place-orders',
        'check-status',
    ]);
    
    Passport::tokensExpireIn(now()->addDays(15));
    Passport::refreshTokensExpireIn(now()->addDays(30));

    Passport::authenticator('api-user', function ($request) {
        return Auth::guard('api-user')->user();
    });
}


  1. Update the api middleware group in your app/Http/Kernel.php file to use the appropriate authentication guard. For example:
1
2
3
4
5
6
7
protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],
];


Change the CreateFreshApiToken middleware to use the desired guard, like CreateApiToken:api-user.

  1. Finally, make sure to update the api middleware in your routes or controllers to use the correct authentication guard:
1
2
3
Route::middleware('auth:api-user')->group(function () {
    // Routes requiring authentication for `api-user` guard
});


That's it! Now you have configured Laravel Passport to work with multiple authentication guards.


How to handle CSRF protection in Laravel Passport?

To handle CSRF (Cross-Site Request Forgery) protection in Laravel Passport, you can follow these steps:

  1. Install Laravel Passport: If you haven't already installed Laravel Passport, you can do so by running the following command in your terminal: composer require laravel/passport
  2. Set up Passport: After installation, set up Passport by running the following command: php artisan passport:install
  3. Use the TransmitCookies middleware: By default, Laravel Passport uses bearer tokens for authentication. To enable CSRF protection, you need to modify the App\Http\Kernel class to include the TransmitCookies middleware. Open the App\Http\Kernel class and add the TransmitCookies middleware to the $middlewareGroups property, as shown below: protected $middlewareGroups = [ 'web' => [ // other middleware here \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // other middleware here ], 'api' => [ // other middleware here 'throttle:60,1', \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // other middleware here ], ];
  4. Use the VerifyCsrfToken middleware: Laravel Passport leverages Laravel's built-in CSRF token mechanism. To enable CSRF protection, you need to apply the VerifyCsrfToken middleware to the required routes. In this case, you may want to add it to your API routes. Open the App\Http\Kernel class and add the VerifyCsrfToken middleware to the $middleware property, as shown below: protected $middleware = [ // other middleware here \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class, ];
  5. Protect your routes: Finally, ensure that the routes you want to protect are covered by the CSRF protection. In Laravel Passport, this typically includes the authentication routes. Open the routes/api.php file and add the CSRF protection middleware to the required routes, as shown below: Route::middleware('auth:api')->group(function () { // authenticated routes here }); By adding the 'auth:api' middleware, your routes will be protected by CSRF.


That's it! By following these steps, you should now have CSRF protection enabled for your Laravel Passport application.


How to define custom scopes using Laravel Passport?

To define custom scopes using Laravel Passport, follow the steps below:

  1. Open the AuthServiceProvider located in app/Providers directory.
  2. Import the Laravel\Passport\Passport facade at the top of the file:
1
use Laravel\Passport\Passport;


  1. Within the boot method of the AuthServiceProvider, use the Passport::tokensCan method to define custom scopes. This method takes an array as an argument, where each key represents the scope and the value represents a human-readable description of the scope:
1
2
3
4
5
Passport::tokensCan([
    'read-posts' => 'Read blog posts',
    'write-posts' => 'Write blog posts',
    // Add more scopes as needed
]);


  1. Run the Passport installation command in the terminal to update the changes:
1
php artisan passport:install


  1. Now, you can include these custom scopes while generating access tokens using the Passport API. For example, you can generate an access token with custom "read-posts" and "write-posts" scopes as follows:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Illuminate\Http\Request;

public function generateToken(Request $request)
{
    $user = $request->user();
    $scopes = ['read-posts', 'write-posts'];

    $token = $user->createToken('Custom Token', $scopes)->accessToken;

    return response()->json(['access_token' => $token]);
}


  1. In your API routes file (routes/api.php), you can protect routes using these custom scopes by chaining the scopes method to the route definition. For instance:
1
2
3
Route::middleware('auth:api')->get('/posts', function () {
    // Only accessible if the access token has the "read-posts" scope
})->scopes('read-posts');


Note: After making changes to the scopes, you need to generate a new encryption key using php artisan key:generate command and update the .env file with the new key.


These steps should help you define custom scopes using Laravel Passport.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

API authentication is an essential aspect of securing your Laravel application. Laravel provides various built-in mechanisms to implement API authentication effortlessly. One widely used method is to leverage Laravel Passport, a full OAuth2 server implementati...
In Laravel, handling user authentication is relatively easy due to the built-in authentication system provided by the framework. The authentication system handles various aspects of user authentication, such as login, registration, password reset, and email ve...
To use a third-party API in WordPress, you can follow these steps:First, you need to find a third-party API that suits your requirements. This could be anything from social media APIs to payment gateway APIs. Once you have identified the API, you need to obtai...