A Complete Guide on How To Install Laravel Passport

author
Kalpesh Prajapati PHP & Java Technology Expert, WPWeb Infotech

Quick Summary: Laravel Passport is an OAuth2-based authentication package that helps developers secure APIs and manage access to protected resources. It provides features such as access tokens, refresh tokens, token scopes, personal access tokens, and OAuth2 grant types. This guide explains what Laravel Passport is, how OAuth2 works, and how to install and configure Passport in Laravel 13. You’ll also learn how to protect API routes and manage token-based authentication. Finally, we compare Laravel Passport vs. Sanctum to help you choose the right authentication solution for your application.

Securing APIs is essential for modern Laravel applications that communicate with mobile apps, third-party services, frontend clients, or external platforms. Laravel Passport simplifies API authentication by providing a complete OAuth2 server implementation, allowing developers to issue, manage, and validate access tokens while controlling access to protected resources.

Passport is a popular choice in Laravel development for projects that require OAuth2 authentication, token-based authorization, user permissions, and secure API access.

In this Laravel Passport tutorial, you’ll learn what Laravel Passport is, how OAuth2 works with Passport, how to install and configure Passport in Laravel 13, and how to protect API routes. We’ll also compare Laravel Passport vs. Sanctum to help you choose the right authentication solution for your project.

What is Laravel Passport?

Laravel Passport is an official package that provides a full OAuth2 server implementation for Laravel applications. Built on top of the League OAuth2 server, it lets you issue, manage, and verify secure API tokens so third-party applications or clients can authenticate with your app’s API. The current major version is Passport 13.x, which requires PHP 8.2 or higher and Laravel 11.35 or higher, so it works with Laravel 11, 12, and 13.

Key Features of Laravel Passport

 The following are the key features of Laravel Passport: 

  • Full OAuth2 Server Compliance: Passport implements standard OAuth2 protocols so external apps and services can securely authenticate with your API. It automatically generates the database tables and encryption keys needed to sign and verify tokens. 
  • Multiple OAuth2 Grant Types: Passport supports several grant types to fit different client needs, including the Authorization Code grant (with PKCE), the Device Authorization grant for input-limited devices, and the Client Credentials grant for machine-to-machine communication. The older password and implicit grants are not recommended, and Passport disables the password grant by default. 
  • Personal Access Tokens: Users can generate self-service API tokens directly from your application without going through a full OAuth2 redirect flow. This works well for developer portals or simple API integrations. 
  • Token Lifecycle Management: You can easily issue, refresh, and revoke access tokens. Refresh tokens allow clients to request new access tokens without forcing users to log in again. 
  • Token Scope: Scopes let you restrict what actions a specific token can perform, such as reading data versus deleting records. You can define custom scopes, set default scopes, and check permissions directly within your routes or controllers. 
  • Route Protection Middleware: Passport integrates directly with Laravel’s built-in authentication guards. You can protect API endpoints and enforce scope requirements using simple route middleware. 
  • JavaScript & SPA Authentication: It includes built-in middleware that attaches a short-lived, encrypted JWT token to cookies, allowing your own frontend Single Page Application (SPA) to consume your API seamlessly without manually managing OAuth tokens. 
  • Lifecycle Events: Passport dispatches events when access tokens or refresh tokens are created or pruned, letting you hook into the authentication process to log activity or revoke older tokens. 

When Should You Use Laravel Passport?

You should use Laravel Passport when your application strictly requires a full OAuth2 server implementation. It is best suited for scenarios where external third-party applications need to connect to your API on behalf of your users, whereas Laravel Sanctum is recommended for simpler first-party authentication. The following are some of the best use cases for Laravel Passport: 

  • Third-party Integrations and Public APIs: Use Passport if you are building a platform or SaaS that allows external apps (like Zapier, Slack, or custom partner integrations) to access your users’ data via OAuth2. 
  • “Sign in With (Your App) Functionality: Choose Passport when you want your application to act as an identity provider, allowing users to log into external websites using their account on your platform. 
  • Granular Permissions with OAuth2 Scope: Use Passport when third-party clients need restricted, user-approved access to specific actions, such as reading profile data without permission to delete records. 
  • Standard OAuth2 Grant Types: Use Passport when your architecture relies on standard OAuth2 flows, such as the Authorization Code grant (with or without PKCE), the Device Authorization grant, or the Client Credentials grant for machine-to-machine communication. Passport also issues refresh tokens, so clients can renew access without asking users to log in again. 

Check the Reddit thread discussion about what you can learn building a Laravel 13 app with laravel/mcp, Passport, Saloon, and PHPArkitect (open source).

What is OAuth2, and how does Laravel Passport use it?

OAuth2 is an open authorization protocol that lets a user grant third-party apps limited access to their resources without sharing their login credentials. 

According to the Laravel Passport documentation, Passport offers a complete OAuth2 server implementation with routes, database migrations, middleware, and Artisan commands: 

  • Setup & Keys: Generates RSA encryption keys (passport:keys) to sign and verify tokens and creates database tables for clients and tokens.
  • Supported Grant Types: Supports Authorization Code, PKCE (–public), Device (–device), Client Credentials (–client), and Personal Access Tokens. The password grant stays disabled until you call Passport::enablePasswordGrant(), and the Laravel docs steer new projects toward Authorization Code with PKCE instead. 
  • Clients and Tokens: Registers OAuth clients (passport:client) with IDs, secrets, and redirect URIs, and issues access/refresh tokens. 
  • Scopes and Middleware: Lets you define token scopes and protect API routes using scope or scopes middleware, or pass fresh API tokens to first-party SPAs via CreateFreshApiToken. 
  • Token Revocation: Allows revoking tokens ( $token->revoke() ) and purging expired or revoked tokens (passport:purge). 

How to Install Laravel Passport

Laravel’s Passport documentation now uses install:api –passport as the main setup command to install Laravel Passport for Laravel 13. The following is the step-by-step process to install Laravel Passport:

1. Install Laravel Passport

You have to run: 

composer require laravel/passport

Passport is Laravel’s official OAuth2 server package. 

2. Run the Passport API install command

Now run: 

php artisan install:api --passport

The command will publish and run the database migrations needed for OAuth clients and access tokens. Also, it generates the encryption keys needed for secure access tokens.

In Passport 13, personal access tokens no longer need a separate personal access client, so you can issue them right after installation. 

3. Update the User Model 

You have to add Passport support in app/Models/User.php: 

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Laravel\Passport\Contracts\OAuthenticatable;

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable implements OAuthenticatable

{

    use HasApiTokens;

}

This will be the current Passport model pattern shown in the Laravel 13 docs.

4. Configure the API guard

To use Passport, set the api guard in config/auth.php: 

<?php

'guards' => [

    'web' => [

        'driver' => 'session',

       'provider' => 'users',

    ],

    'api' => [

        'driver' => 'passport',

        'provider' => 'users',

    ],

],

This will command Laravel to authenticate API requests using Passport tokens. 

5. Add API Routes 

Define API endpoints in routes/api.php, if you have it in your app. Laravel’s API routing is enabled through the install:api flow, which creates the API route file. 

For Example: 

<?php

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

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

    return $request->user();

});

6. Generate Your Token in Your Login Logic 

For Example: 

<?php

$token = $user->createToken('API Token')->accessToken;

Laravel Passport supports creating personal access tokens directly from the authenticated user model. 

7. Send the Token in API Request 

Use the following tokens in the request header: 

Http

Authorization: Bearer your_access_token

Accept: application/json

Protected routes use auth:api, which will then allow access only when the token is valid. 

8. Define Scopes and Token Expiry (Optional) 

You can define scopes and token expiry time in AppServiceProvider

<?php

use Carbon\CarbonInterval;

use Laravel\Passport\Passport;

public function boot(): void

{

    Passport::tokensCan([

        'user:read' => 'Read user profile',

        'posts:create' => 'Create posts',

    ]);

    Passport::tokensExpireIn(CarbonInterval::days(15));

    Passport::refreshTokensExpireIn(CarbonInterval::days(30));

    Passport::personalAccessTokensExpireIn(CarbonInterval::months(6));

}

Laravel Passport officially supports scopes and configurable token expiration. 

9. Test the Flow 

The following should be your test flow:

  1. User logs in 
  2. Laravel creates a Passport token
  3. Frontend/mobile apps store the token 
  4. Client sends Bearer token on protected API requests 
  5. Laravel validates the token through Passport 

Example of Login API with Passport 

The following is a clean way to introduce Passport: it shows a login flow that issues a token after validating the user.

Controller Example

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

use App\Models\User;

use Illuminate\Http\JsonResponse;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Hash;

class AuthController extends Controller

{

    public function login(Request $request): JsonResponse

    {

        $request->validate([

            'email' => ['required', 'email'],

            'password' => ['required', 'string'],

        ]);

        $user = User::where('email', $request->email)->first();

        if (! $user || ! Hash::check($request->password, $user->password)) {

            return response()->json([

                'message' => 'Invalid credentials.',

            ], 401);

        }

        $token = $user->createToken('Web Login Token', ['profile:read'])->accessToken;

        return response()->json([

            'message' => 'Login successful.',

            'token_type' => 'Bearer',

            'access_token' => $token,

            'user' => $user,

        ]);

    }

    public function profile(Request $request): JsonResponse

    {

        return response()->json([

            'user' => $request->user(),

        ]);

    }

    public function logout(Request $request): JsonResponse

    {

        $request->user()->token()->revoke();

        return response()->json([

            'message' => 'Logged out successfully.',

        ]);

    }

}

Laravel Passport supports issuing personal access tokens through createToken() on the user model, and token revocation is a part of the built-in workflow. 

API Routes 

<?php

use App\Http\Controllers\Api\AuthController;

use Illuminate\Support\Facades\Route;

Route::post('/login', [AuthController::class, 'login']);

Route::middleware('auth:api')->group(function () {

    Route::get('/profile', [AuthController::class, 'profile']);

    Route::post('/logout', [AuthController::class, 'logout']);

});

Laravel Passport integrates with Laravel’s auth:api middleware when the api guard is configured to use the passport driver. 

Example Request 

curl --request POST \

  --url http://127.0.0.1:8000/api/login \

  --header 'Accept: application/json' \

  --header 'Content-Type: application/json' \

  --data '{

    "email": "[email protected]",

    "password": "password"

}'

Example Response 

{

  "message": "Login successful.",

  "token_type": "Bearer",

  "access_token": "eyJ0eXAiOiJKV1QiLCJh...",

  "user": {

    "id": 1,

    "name": "John Doe",

    "email": "[email protected]"

  }

}

The client can now include that access token in the Authorization: Bearer … header for protected requests. Passport uses those bearer tokens to authorize access to API routes.

Laravel Passport vs. Laravel Sanctum

Features Laravel Passport Laravel Sanctum 
Primary Purpose Full OAuth2 authorization server for external links (third-party) Lightweight authentication for your own clients (first-party) 
Protocol Full OAuth2 specifications (grants, auth codes, refresh tokens) Simple API tokens & cookie-based sessions 
Ideal Use Cases Public APIs, “Login with Your App” integrations, partner apps acting on a user’s behalf SPAs (React/Vue/Inertia), native mobile apps, simple personal access tokens 
Token Types Cryptographically signed JWTs (JSON Web Tokens) with multiple OAuth tablesHashed random strings stored in a single database table (no JWT overhead) 
Permissions Granular OAuth2 scopes with user consent screens Simple token “abilities” (e.g., server:update) 
Setup & Overhead Heavy; requires encryption keys, client secrets, and complex grant flowsMinimal; fast to configure with tiny database footprint 
Simplicity vs. StandardizationAdds significant boilerplate, which is only worthwhile when external developers expect industry-standard OAuth2 endpointsAvoids the complexity of OAuth2 handshakes, giving first-party SPAs seamless CSRF-protected cookie authentication when hosted on the same top-level domain
Token LifecycleManages short-lived access tokens paired with refresh tokens, which adds security for third-party integrations but requires extra frontend logicStraightforward; they stay valid until revoked or expired, making them easy to manage for mobile apps or CLI tools

Conclusion 

Laravel Passport is a powerful solution for securing APIs with OAuth2 authentication, offering access tokens, refresh tokens, scopes, and flexible authorization mechanisms. It helps developers manage API access securely across web applications, mobile apps, and third-party integrations. While Passport is ideal for applications requiring full OAuth2 capabilities, Laravel Sanctum may be a better fit for simpler authentication needs.

Choosing the right authentication approach is only one part of building a secure and scalable Laravel application. If you’re planning to hire a Laravel expert to build a custom Laravel application, install Laravel Passport to authenticate your app, integrate secure APIs, or upgrade your existing project, we can help you turn your requirements into reliable, high-performing solutions. With expertise in Laravel development, API integration, and custom web application development, WPWeb Infotech helps businesses build applications tailored to their goals and future growth.

FAQs

Is Laravel Passport free?

Yes, Laravel Passport is free. It is an open-source software released under the MIT License. You can set it up by installing Composer or running Artisan commands (such as php artisan install:api –passport in newer Laravel versions).

Is Laravel Passport secure?

Yes, Laravel Passport is secure when configured properly. It implements OAuth2 (built on the League OAuth2 server) and uses RSA encryption keys to sign and verify tokens.

Why Use Laravel Passport?

You should use Laravel Passport when your application needs to act as a full OAuth2 server; specifically, when third-party apps need to access your users’ data securely without handling their passwords.

Can Passport be used without OAuth knowledge?

Yes, depending on which ‘Passport’ you mean, you can use Passport.js without OAuth knowledge, while Laravel Passport is built specifically around OAuth2.

Does Passport support refresh tokens?

Yes, both Laravel Passport and Laravel Passport.js support refresh tokens, though they handle them differently depending on the framework and strategy.