Learn how to set up Laravel Sanctum for secure API authentication in 2025. This guide will help you protect your RESTful endpoints using token-based authentication — ideal for SPAs and mobile apps.
🔐 What Is Laravel Sanctum?
Laravel Sanctum is a simple package for API token authentication. It's perfect for single-page apps, mobile apps, or any frontend consuming your Laravel API.
🚀 Why Use Sanctum for API Auth?
- Lightweight and easy to set up
- Works seamlessly with SPAs (Vue/React)
- Perfect for mobile APIs
- No need for OAuth complexity
- Secure and well-integrated with Laravel
⚙️ Step 1: Install Laravel Sanctum
composer require laravel/sanctum
Publish Sanctum’s config and migration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
🔧 Step 2: Configure Middleware
In app/Http/Kernel.php, update the api middleware group:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
🧪 Step 3: Set Up Auth Scaffolding
You can use Laravel Breeze to set up API authentication logic:
composer require laravel/breeze --dev
php artisan breeze:install api
php artisan migrate
🔑 Step 4: Issue Tokens
In your login controller, issue a token on successful login:
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return response()->json(['error' => 'Invalid credentials'], 401);
}
return $user->createToken('auth_token')->plainTextToken;
Use the token in your API headers like this:
Authorization: Bearer {token}
🔒 Step 5: Protect Routes
In routes/api.php:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
🧼 Revoking Tokens
To revoke all of a user's tokens:
$user->tokens()->delete();
🧪 Testing Your API Auth
- Register a user
- Log in and grab the token
- Call protected routes with the token
✅ Final Tips for Sanctum
- Use HTTPS in production for security
- Use Laravel Horizon to monitor token usage
- Sanctum is ideal for SPAs and mobile apps
- For OAuth or third-party access, use Laravel Passport instead
👨💻 Ready to Secure Your API?
Laravel Sanctum is the simplest and most efficient way to add API authentication to your Laravel app in 2025. Whether you're building a SPA, mobile app, or custom API dashboard, Sanctum gives you the tools to stay secure and scalable.
Need help setting up Laravel authentication?
Contact me here →