Laravel Sanctum Authentication

matt
Matthew Gros · Oct 22, 2025

TLDR

Use Sanctum for SPA auth (cookies) or API tokens. Simpler than Passport for most cases.

Laravel Sanctum Authentication

Simple Auth for SPAs and APIs

Sanctum is lighter than Passport. Perfect for most apps.

Installation

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

SPA Authentication (Cookies)

For same-domain SPAs:

// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', fn() => auth()->user());
});
// Frontend - get CSRF cookie first
await fetch('/sanctum/csrf-cookie');

// Then login
await fetch('/login', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify({ email, password })
});

// Authenticated requests work automatically
const user = await fetch('/api/user', {
    credentials: 'include'
}).then(r => r.json());

API Token Authentication

For mobile apps or third-party access:

// Generate token
$token = $user->createToken('mobile-app')->plainTextToken;

// With abilities
$token = $user->createToken('api', ['read', 'write'])->plainTextToken;

// Check ability
if ($user->tokenCan('write')) {
    // ...
}
// Use token in requests
fetch('/api/user', {
    headers: {
        'Authorization': `Bearer ${token}`
    }
});

Revoking Tokens

// Current token
$request->user()->currentAccessToken()->delete();

// All tokens
$user->tokens()->delete();

// Specific token
$user->tokens()->where('id', $tokenId)->delete();

Configuration

// config/sanctum.php
'expiration' => 60 * 24 * 7, // 7 days

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.