Laravel Sanctum vs Laravel Passport

March 25, 2025
Written by
Lucky Opuama
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Laravel Sanctum vs Laravel Passport

It is no longer news that security is an essential factor when developing an application. As applications evolve, so do their authentication needs. This is why Laravel offers your application two important “locks and keys”: Laravel Passport and Laravel Sanctum.

Laravel Passport is a complete OAuth2.0 implementation designed for powerful, API-driven apps that require sophisticated permissions, token lifecycles, and third-party interfaces. Laravel Sanctum, on the other hand, is a simpler, featherweight solution for securing Single-Page Applications (SPAs) and first-party applications, avoiding the complexity of OAuth2.

Laravel Passport and Laravel Sanctum are two specialized authentication tools tailored to meet different security needs in your applications. For complex APIs with third-party integrations, like a healthcare system, Laravel Passport provides robust OAuth2 features. For simpler SPAs, like an online learning platform, Laravel Sanctum offers lightweight, token-based authentication. Just as you’d choose different locks for various needs, each tool is tailored for specific security requirements in web development.

In this comparison, we'll look at the key features, use cases, and technical differences between each, directing you to the best option for your application's security needs.

What kind of authentication package do I need?

The API you are building provides sensitive data, such as healthcare or financial information, to various clients. To ensure security, you'll need to restrict the access for certain users, unless you want to make it freely accessible to everyone.

Before deciding on the authentication system you need, it's essential to understand why authentication is important. Authentication ensures that only verified users can access certain parts of your application, protecting sensitive information and resources. Also, it helps maintain user privacy, secure transactions, and prevents unauthorized access or data breaches.

Now what kind of authentication package do you need? Let’s consider the following scenarios:

  • Single-Page Applications (SPAs): These are web apps that load a single HTML page and dynamically update content using JavaScript APIs when the user interacts with them. SPAs are a lightweight, token-based solution that is suited for Laravel Sanctum. Scantum enables safe, simple authentication without the overhead of OAuth2, making it ideal for SPAs with a frontend and backend under the same control.
  • Traditional web applications: These are server-rendered apps in which every user activity, such as moving between pages or submitting a form, sends a request to the server which processes it, generates an HTML response, and returns it to the browser. Laravel's built-in session-based authentication is usually the best option for this type of application. However, Laravel Sanctum can improve the security and flexibility of traditional apps, especially when serving additional APIs and managing numerous devices.
  • APIs:  These are backend services developed to serve data and perform operations through APIs. Their primary objective is to offer standardized, secure endpoints for various clients to access and interact with, focusing solely on data processing and response delivery. API-only applications often rely on token-based authentication, where clients authenticate once and receive a token for subsequent requests. Common token-based authentication methods include OAuth2 and personal access tokens, both supported by Laravel Passport to provide robust security and control over API access.
  • Mobile applications: These applications have unique authentication requirements because of the nature of mobile devices and their dependency on external APIs. Unlike web applications, mobile apps often require secure, long-lasting sessions and need to handle varied connectivity levels seamlessly. Laravel Passport is the preferred choice for mobile apps, offering OAuth2 support for secure, persistent access with flexible permissions and refresh tokens. However, if your app doesn’t require OAuth2’s complexity, Laravel Sanctum can serve as a better alternative, providing simple token-based authentication without the overhead of refresh tokens.

Prerequisite

To follow along with this tutorial, you will need the following:

Set up and configure Laravel Passport

To install Laravel Passport, first create a new Laravel project and navigate to the new project directory. You can do this by running the following commands in your terminal:

composer create-project laravel/laravel laravel-passport-example
cd laravel-passport-example

Now, you can install and configure Passport. To do that, run the following command:

php artisan install:api --passport

This command does more than install Laravel Passport; it also configures your database, sets up the required tables, and generates the encryption keys needed for creating secure access tokens.

During installation, you will be prompted to choose whether to use UUIDs for all client IDs. Press Enter to proceed with the default option (no).

Next, navigate to the app/Models directory, open the User.php file, and update with the following code.

use Laravel\Passport\HasApiTokens;

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

The HasApiTokens trait allows you to inspect the authenticated user's token and scopes, enabling your model to validate permissions and access levels. Now, navigate to the config/auth.php file, and add the following configuration file:

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

This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests.

Now, Laravel Passport is fully configured and ready for the next phase of action in building a simple user authentication. Create the AuthController by running the command below:

php artisan make:controller AuthController

Next, open the AuthController.php file in your app/Http/Controllers directory and replace its contents with the following code:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        $token = $user->createToken('authToken')->accessToken;
        return response()->json(['token' => $token], 201);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);
        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }
        $user = Auth::user();
        $token = $user->createToken('authToken')->accessToken;
        return response()->json(['token' => $token]);
    }
}

The controller acts as the brain of the application’s authentication system. It holds two core methods

  • register: It creates a new user in the system and returns an access token for secure communication.
  • login: It authenticates an existing user and, upon successful credential validation, returns an access token for continued access.

Next, let's customize the routes provided by Laravel Passport. You can do this by calling Passport::ignoreRoutes() in the register() method of your application's AppServiceProvider. Navigate to the app/Providers directory, open the AppServiceProvider.php file, and update the register() method to match the code below:

public function register(): void
{
    \Laravel\Passport\Passport::ignoreRoutes();
}

Next, navigate to the routes directory, open the api.php file, and update it to match the following code:

<?php

use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Http\Controllers\AccessTokenController;
use Laravel\Passport\Http\Controllers\AuthorizedAccessTokenController;

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

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

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

Route::group([
    'prefix' => config('passport.path', 'oauth'),
], function () {
    Route::post('/token', [
        'as' => 'passport.token',
        'uses' => [AccessTokenController::class, 'issueToken']
    ]);
    Route::middleware('auth:api')->group(function () {
        Route::get('/tokens', [
            'as' => 'passport.tokens.index',
            'uses' => [AuthorizedAccessTokenController::class, 'forUser']
        ]);
        Route::delete('/tokens/{token_id}', [
            'as' => 'passport.tokens.destroy',
            'uses' => [AuthorizedAccessTokenController::class, 'destroy']
        ]);
    });
});

The route above comprises the following:

  • Authenticated user route: This route retrieves the authenticated user’s information, ensuring only users with valid tokens can access it.
  • User registration and login routes: These routes handle user registration and login, providing access tokens for authenticated access.
  • OAuth token management routes: These routes manage token operations, including creation, listing, and deletion, using Laravel Passport to enable secure user authentication.

Now, launch the application by running the following command on your terminal.

php artisan serve

After launching the application, open it in a browser of your choice. By default, the Laravel application is available on http://127.0.0.1:8000. You should see the same image below.

Test the Laravel Passport authentication endpoints with Postman

Now, let's see if the Laravel Passport user authentication is working by running a test with Postman, by following the steps below:

  • Open Postman
  • Set the URL as http://127.0.0.1:8000/api/register
  • Set the request type to POST
  • Click the Body tab, select raw, then choose JSON format
  • Add your registration details
  • Click Send to send the request

When you send the request, you will receive a response with a token if it's successful.

Follow the example image below to login and you will get the same result.

Set up and configure Laravel Sanctum

To install Laravel Sanctum run the following command in your terminal:

php artisan install:api

This command will install Laravel Sanctum along with the necessary packages. During the installation, you’ll see a prompt stating that 'One new database migration has been published.' When asked, 'Would you like to run all pending database migrations?', proceed with the default answer: yes.

Next, navigate to the app/Models directory, open the User.php file, and add the following code:

use Laravel\Passport\HasApiTokens;

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

This trait will allow you to inspect the authenticated user's token, enabling your model to validate permissions and access levels easily.

Now, run the following command to create the AuthController.

php artisan make:controller AuthController

Next, navigate to the app/Http/Controllers directory, open the AuthController.php file you just created, and replace with the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json(['token' => $token], 201);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);
        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }
        $user = User::where('email', $request->email)->first();
        $token = $user->createToken('auth_token')->plainTextToken;
        return response()->json(['token' => $token]);
    }
}

This code validates, authenticates, and generates tokens using Laravel Sanctum. Next, navigate to the routes directory, open the api.php file, and add the following command route.

<?php

use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

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

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

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

Now, launch the application by running the following command on your terminal.

php artisan serve

After launching the application, open it in a browser of choice to verify if there are no errors. By default, it's available on http://127.0.0.1:8000.

Test Laravel Sanctum authentication endpoints with Postman

To properly test your application's authentication endpoints with Postman, follow these steps:

  • Open your Postman application and paste this URL: http://127.0.0.1:8000/api/register using a post request.
  • Navigate to body and select raw, then choose JSON format, and then add your registration details as in the image below:

When you send the request, you will receive a response with a token.

Use the same method as shown in the image below to log in and you will get the same result.

Key differences

Both Laravel Passport and Laravel Sanctum provide robust API authentication solutions, but they are tailored to various purposes and types of applications. The primary distinctions are based on their use cases, complexity, token type, scope, and the level of authentication provided, which are outlined in the table below.

Which package should you choose?

After reviewing the key features, selecting the right package for your application becomes easier, as it ultimately depends on your project's specific requirements. By understanding the strengths and limitations of Laravel Passport and Laravel Sanctum, you can make an informed choice, ensuring your application remains secure and user-friendly with the best-suited authentication solution.

Laravel Passport is the go-to choice for API-based, multi-client applications that require OAuth2 authentication with advanced token control and access management.

In contrast, Laravel Sanctum works best for SPAs and first-party applications where a lightweight, token-based, or session-based solution is sufficient for security and simplicity.

That's a comparison of Laravel Sanctum and Laravel Passport

This tutorial clarifies that each package has its strengths and limitations, making them suited for different use cases based on specific project demands. By assessing the distinct features of Laravel Passport and Laravel Sanctum, you can choose the authentication solution that best aligns with your application’s requirements, security needs, and client structure.

A clear understanding of each package role will enable you to establish a secure and reliable authentication system. Always stay updated with the latest developments in Laravel to make informed choices and adapt to developing security challenges. Happy coding!

Lucky Opuama is a software engineer and technical writer with a passion for exploring new tech stacks and writing about them. Connect with him on LinkedIn.