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
