Laravel Sanctum makes authentication easy for web, mobile, and single-page apps. It's perfect for modern SPAs, mobile apps, or traditional websites. Sanctum simplifies user login, API access, and session management.
Modern apps need secure authentication without extra complexity. Laravel Sanctum offers a simple solution. It eliminates the need to manage tokens, routes, and middleware manually. It works well with Laravel, saving time while keeping security high.
Learn how Laravel Sanctum improves your authentication workflows. This guide will cover its main features, setup, and best practices. It's designed to help you create reliable, scalable authentication systems for any project.
Laravel Sanctum is a simple way to keep web and mobile apps safe. It makes token-based authentication easy, without the hassle of OAuth. It's great for SPAs and mobile apps, helping manage user sessions and API access.
Laravel started with basic login systems. Then, Passport came for OAuth2 APIs. But, many apps don't need all that. Sanctum fills the gap with key features like API tokens and cookie handling for SPAs.
Choose Sanctum for token-based access in APIs or SPAs without OAuth2 needs. It's faster to set up than Passport, saving time. It's ideal for apps needing simple, secure authentication.
Before starting with laravel sanctum setup, make sure your setup is ready. Laravel Sanctum works best with Laravel 7.x or higher and PHP 7.3+. These versions ensure compatibility with Sanctum’s features and security updates.
composer show laravel/framework
.php -v
to verify PHP 7.3+ is installed..env
and migrations are current.If starting from scratch, create a new Laravel project with: composer create-project --prefer-dist laravel/laravel your-project-name
. If you have an existing app, update dependencies first.
A working authentication system is crucial. Sanctum uses Laravel’s default auth scaffolding. Run php artisan make:auth
if you haven’t set up routes and views. Knowing about JSON Web Tokens (JWT) helps understand how Sanctum handles API tokens. But don’t worry, the documentation will guide you step by step.
Make sure these basics are covered before moving to laravel sanctum implementation. A solid foundation makes integration smoother. Ready? Let’s proceed to installation in the next section!
Starting your laravel sanctum integration journey is easy. This laravel sanctum tutorial will show you how to add Sanctum to your Laravel app. We'll make sure each step is clear and easy to follow.
First, open your terminal and run the Composer command to install Sanctum. Use:
composer require laravel/sanctum
This command adds Sanctum to your composer.json
and gets the needed dependencies. Laravel then registers Sanctum’s service provider. This sets up the base for authentication features.
After installing, run:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
This command publishes Sanctum’s core files. You can now edit them. You won't need to do any manual setup unless you want to change settings later.
Next, generate Sanctum’s configuration file by running:
php artisan vendor:publish --tag=sanctum-config
This creates a sanctum.php
file in
config/
. You can adjust CORS policies and authentication guards here. This lets you tailor your app’s settings.
Run the migration command to create Sanctum’s tables:
php artisan migrate
This command creates important tables like personal_access_tokens
. These tables store authentication data. You can only modify these migrations if you need custom columns or constraints.
With these steps, your app is now ready to use Sanctum’s authentication. Keep this guide close as we dive into configuration and implementation next!
Getting good at laravel sanctum authentication starts with setting it up right. First, tweak the sanctum.php config file. Here are the main settings to adjust:
stateful
array. Example: ['http://localhost:3000', 'https://api.yourapp.com']
expiration
value (minutes). Default 43200 (28.8 hours)Update your .env
file with:
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=yourdomain.com
(for multi-domain setups)For single-page apps, tweak CORS in
cors.php
:'paths' => ['api/*', 'sanctum/csrf-cookie'],Enable credentials with
supports_credentials: true
Middleware like HandleStatefulRequests
helps manage API requests. Use php artisan route:list
to check middleware. Always test token expiration with Postman or browser tools.
Remember, wrong CORS settings lead to 419 errors. Check Laravel's official docs for environment-specific tweaks. Small adjustments here make laravel sanctum authentication secure for SPAs and APIs.
API tokens are key to secure user access in Laravel Sanctum. This guide covers how to create, manage, and protect laravel sanctum tokens. It also focuses on maintaining strong laravel sanctum security. Follow these steps to set up a token-based system for your app.
Begin by giving tokens to users when they register or log in. Laravel makes it easy to generate tokens with just a few lines of code:
$user = User::find(1); $token = $user->createToken('API Access');
Keep the token safe on the client side for future use. Always check tokens on each API call to make sure they're real.
Use Sanctum's ability system to set up detailed permissions. When creating tokens, assign specific actions like ['read-posts', 'update-profile']
:
createToken('Token Name', ['scope1', 'scope2'])
to limit access.hasTokenAbility('scope')
in controller methods.Limiting abilities helps if a token is leaked, making your laravel sanctum security better.
Managing token lifecycles is crucial. Revoke tokens right after a user logs out:
// Revoke all tokens $user->tokens()->delete(); // Revoke a single token $token->revoke();
Refresh tokens to give new ones without needing to log in again. Create a refresh endpoint to get a new token after checking the old one. Change tokens often to lower the risk of unauthorized access.
"Token revocation and rotation are essential for minimizing exposure after potential breaches." — Laravel Sanctum Documentation
Always store tokens in encrypted HTTP-only cookies for SPAs and mobile apps. This keeps them safe from client-side threats. Use these steps with rate limiting and CORS policies for even more security.
Laravel Sanctum makes Single Page Application (SPA) authentication easy with cookie-based sessions. It's better than token-based systems because it automatically handles secure cookies. This is great for Vue.js or React apps. First, set up routes for laravel sanctum login and logout.
web.php
for authentication flows.For the laravel sanctum login process, create a login route. It should authenticate users and return a session cookie:
Example PHP route:
Route::post('/login', function (Request $request) { // Validate credentials Auth::attempt($request->only('email', 'password')) ? return 'Logged in' : abort(401); })->middleware('guest');
On the frontend, send login requests with JavaScript:
Vue.js example:
axios.post('/login', { email, password }) .then(response => { // Redirect to dashboard });
Sanctum automatically protects against CSRF when headers are set. Include X-XSRF-TOKEN
in AJAX requests. This keeps security high without needing to manage tokens manually.
Use Sanctum’s middleware to protect routes. This ensures only logged-in users can access resources. Test it by logging in and seeing if the session stays active across page loads.
Mobile apps need secure but easy-to-use login methods. Laravel Sanctum makes this easier by using tokens for mobile apps. We'll look at how to set this up for iOS, Android, or Flutter apps.
Laravel Sanctum for mobile starts with creating secure API tokens. Use createToken()
to make tokens linked to user accounts. For example:
Keep tokens safe using iOS’s Keychain or Android’s Keystore. Never put tokens in the app code.
Every request from mobile apps must have the Sanctum Bearer token in headers. Here's how to do it:
Authorization: Bearer {token}
to HTTP requests.Remember, Sanctum uses these headers to check each API call.
Keep users logged in with automatic token refresh. Schedule checks to:
revokeTokens()
.Save refreshed tokens in secure, encrypted storage to prevent unauthorized access.
Strong laravel sanctum security is more than just setting it up. It's about turning good code into secure code. Let's look at three steps to make your app more secure without making things too complicated.
“Security is a shared responsibility—Laravel Sanctum provides tools, but implementation details matter most.”
Stop brute-force attacks by limiting login and API requests. Laravel Sanctum works well with Laravel's throttling middleware. Add throttle:60,1
to routes to limit 60 requests per minute.
For sensitive areas like password resets, use throttle:5,1
to block fast retries.
Cross-Origin Resource Sharing (CORS) mistakes can let unauthorized access in. Set up CORS in config/cors.php
to only allow trusted domains. Use:
https://yourapp.com
).supports_credentials = true
for secure token sending.In production, turn off wildcard origins to stop unauthorized cross-domain requests.
Adjust security for each environment with .env
variables:
SANCTUM_STATEFUL_DOMAINS
to match current domains in staging/production.API_TOKEN_LIFETIME
from 30 days to 7 days in production.APP_DEBUG
in live environments to hide system errors from users.These settings help developers in testing while keeping live systems safe.
Even with a solid laravel sanctum setup, unexpected issues can arise. Let’s tackle the most frequent hurdles developers face and how to resolve them quickly.
auth:sanctum
is correctly applied to routes. Missing headers like Accept: application/json
can block token validation.config/cors.php
. Ensure Sanctum::stateful()
includes your frontend domains to avoid cross-origin blocks.file
aren’t configured for your environment.sanctum.php
routes are registered via php artisan vendor:publish
and routes are correctly imported.A quick validation checklist:
php artisan route:list
to confirm Sanctum routes are registered.Auth::guard('sanctum')->user()
in controllers..env
variables for correct API domain listings.“Sanctum issues often stem from overlooked configuration details—not code errors,” says Laravel community lead Taylor Otwell. “Methodical checks save time.”
For persistent errors, enable debug mode with APP_DEBUG=true
to inspect raw server responses. Review browser console logs for network failures during laravel sanctum login attempts. If tokens aren’t refreshing, check abilities
in token creation and ensure personal_access_tokens
migration exists.
Remember: Sanctum integrates tightly with Laravel’s core. Most fixes involve cross-verifying middleware, CORS policies, and session storage settings. Take it step by step, and you’ll resolve even the trickiest issues.
Laravel Sanctum makes modern laravel authentication easier. It offers a single method for APIs, SPAs, and mobile apps. This approach cuts down setup time and keeps security strong.
It works well for both public API endpoints and single-page applications. Sanctum's flexibility meets different project needs.
Developers can now build secure solutions easily. They don't need to deal with complicated setups. Real projects benefit from Sanctum's token and session management.
Look into adding social authentication or two-factor authentication. These can make your setup even better.
For more, check out Laravel's Sanctum documentation. You can also use Laravel Breeze for UIs. Always keep security in mind, like using environment settings and updating tokens.
Secure authentication builds trust with users. It's not just about tech; it's about user confidence.
Try Sanctum in side projects or your current apps. See how it handles loads or fits into mobile/web projects. Each step improves your skills in laravel authentication.
The Laravel world keeps changing, but Sanctum stays a top choice. It helps developers balance speed and security.