
The first decision with Laravel Sanctum is whether your application needs a session cookie or an API token. Getting that right saves a lot of authentication code and makes the problems that follow easier to diagnose.
We use Sanctum in our SaaS backends, including a platform with tenant subdomains and an internal tool that rotates integration tokens. Those applications need different authentication flows. This guide covers both, with particular attention to permissions, expiry and the browser configuration that can make a working login appear broken.
Choose the authentication flow before writing code
| Application | Starting point | Credential sent with requests |
|---|---|---|
| Your own first-party SPA | Sanctum's stateful session authentication | Session cookie, with CSRF protection for state-changing requests |
| Mobile app or an integration using personal access tokens | Sanctum API tokens | Bearer token in the Authorization header |
| Server-rendered Laravel application | Laravel session authentication, often through a starter kit | Session cookie |
| An API that needs OAuth2 delegation | Laravel Passport | Credentials defined by the chosen OAuth2 flow |
For your own SPA, use the session flow rather than issuing a personal access token at login and storing it in the browser. Sanctum supports this even when the frontend lives in a separate repository. Its documented SPA setup requires the frontend and API to share a root domain, such as app.example.com and api.example.com.
A separate frontend repository alone is not a reason to choose bearer tokens. We discuss that wider decision in our Laravel frontend architecture guide.
Install Sanctum and check your application version
For current Laravel applications, the API installation command installs Sanctum and prepares API routing:
php artisan install:api
php artisan migrate
The examples below use the modern bootstrap/app.php configuration style. Before adapting an older application, check its installed Laravel and Sanctum versions and use the matching Sanctum documentation. Middleware registration differs in older Laravel skeletons.
Issue API tokens with explicit abilities and expiry
Add Sanctum's HasApiTokens trait to your authenticatable user model. The following is the relevant model setup; retain the other traits and configuration your application needs.
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
Once your application has securely authenticated the user and authorised token creation, issue a token with the abilities the integration actually needs. In this example, $user is that authenticated user, not a user selected from an untrusted request parameter
$token = $user->createToken(
'reporting-integration',
['reports:read'],
now()->addWeek(),
);
return ['token' => $token->plainTextToken];
Sanctum stores a hash of the token. Return the plaintext value when it is created, keep it out of logs and send it over HTTPS. Subsequent API requests supply it as Authorization: Bearer TOKEN.
The third argument sets an individual expiry in current Sanctum. The package persists it as expires_at. Tokens otherwise have no expiry by default; you can also set a global lifetime through Sanctum's expiration configuration, in minutes. A per-token date does not override a shorter global lifetime.
Deleting expired records is a separate housekeeping step. Schedule sanctum:prune-expired if you use expiring tokens. Expiry enforcement should not depend on that cleanup job running.
Check permissions beyond the token
A token ability limits what that credential may do. It does not establish that its owner may access every record of the matching type.
Protect API routes with auth:sanctum. If you use Sanctum's ability middleware, register the aliases in the existing middleware configuration:
use Illuminate\Foundation\Configuration\Middleware;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
// Inside your existing Application configuration chain:
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'abilities' => CheckAbilities::class,
'ability' => CheckForAnyAbility::class,
]);
})
abilities requires every listed ability; ability accepts any listed ability. Use the same exact ability name at creation and enforcement, such as reports:read in both places. Follow that check with a policy or gate that verifies the user's access to the requested report and tenant.
This distinction matters especially when a route accepts both modes. For a first-party session request, Sanctum's tokenCan() returns true by design. Your policy still has to decide whether that user may perform the action.
Connect a first-party SPA through session authentication
Enable stateful API middleware in your existing bootstrap/app.php configuration:
->withMiddleware(function (Middleware $middleware): void {
$middleware->statefulApi();
})
Merge this with the application's existing middleware callback. Configure Sanctum's stateful domains for the trusted frontend hosts, including ports during local development. For a frontend on another subdomain, allow its exact origin in CORS and enable credentialed requests. Configure the session cookie for the trusted domains that need to share it.
With Axios, enable credentials and XSRF handling before initialising CSRF protection and submitting the login request:
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
await axios.get('https://api.example.com/sanctum/csrf-cookie');
await axios.post('https://api.example.com/login', {
email,
password,
});
const response = await axios.get('https://api.example.com/api/user');
The API must provide a session-based login endpoint. Use an established authentication implementation, such as Laravel Fortify, and retain login throttling, validation and session regeneration. The final request also assumes you have an authenticated /api/user route. The client snippet is a request sequence, not a complete authentication application.
Session-authenticated, state-changing requests need CSRF protection. A bearer-token API request does not use the browser session cookie in the same way, so saying that every Sanctum API request has CSRF protection is misleading. Do not disable CSRF protection to make an SPA login work.
Debug 401 and 419 responses by following the request
In a decoupled SPA, start with the browser's network panel. Check whether the CSRF request sets its cookies, whether login sends the required cookies and XSRF header, and whether the next API request sends the authenticated session cookie.
- 401: check the session or token first, then the route's guard, trusted stateful domains and whether the browser sent credentials.
- 419: investigate CSRF and session mismatches. A missing XSRF header is one cause; an expired session or a cookie that cannot reach the API can produce the same symptom.
- Cross-origin failures: check the allowed origin, credential support, hostnames, ports and cookie settings together. Retest with a clean browser session after changing the configuration.
Our tenant-subdomain application makes cookie scope particularly important. A shared parent-domain cookie can support an intended login across trusted subdomains, but it also expands the trust boundary. Choose that scope deliberately. Authentication never replaces checking the user's membership of the tenant requested on each call.
Keep request state separate under Octane
Octane keeps workers alive between requests and resets first-party framework state. The risk to investigate is application code that retains a user, request or tenant in a singleton or other shared state. Sanctum does not need a blanket manual reset workaround.
Pass request-specific values where they are needed rather than capturing them during worker boot. Add a regression check that sends requests for user A, user B and a guest through the same worker and verifies the identity and tenant each request receives. Our Octane guide covers the broader worker-lifecycle trade-offs.
Rotate integration tokens without losing ownership checks
In our internal tool, integration tokens belong to a repository or integration model rather than the standard User model. We rotate them with a short overlap so the consuming integration can switch credentials before the old token expires.
That is an application design, not a promise that adding a trait makes any Eloquent model suitable for authentication. Check the token owner's authentication contract, provider configuration and authorisation rules. Current Sanctum's token trait and guard support the underlying mechanics, but your application must decide what that integration can access.
Create the replacement, update the consumer securely, confirm that it works, then revoke the previous token. Use a short, explicit overlap when continuity requires it. Revoke a compromised credential immediately rather than preserving that grace period.
Test both authentication paths before release
Use Sanctum::actingAs() for focused permission tests, then add tests that exercise the real credential path. A mocked authenticated user cannot tell you whether the browser receives its cookies or a revoked bearer token is still accepted.
- A valid token can perform its permitted action; a missing ability is rejected.
- The same ability cannot bypass another user's or tenant's policy.
- Expired and revoked credentials fail, including when global and individual expiry are both configured.
- The SPA can log in and out; state-changing requests with invalid CSRF credentials fail.
- If using Octane, a later request cannot inherit an earlier user's identity or tenant.
Sanctum keeps the credential layer small. The rest of the work is making ownership, permissions, and request boundaries explicit. If you need help reviewing an existing implementation, our Laravel team can work through those decisions with you.






