Sanctum is often pitched as "simple API authentication for Laravel," which pushes a lot of teams to install it without realizing it actually covers two distinct mechanisms with different security models. Conflating them is the single most common source of hard-to-diagnose authentication bugs and vulnerabilities in production.

Two mechanisms, not one

Sanctum handles two separate use cases, documented as such but often used without a clear distinction in the codebase:

  1. API tokens (personal access tokens): an opaque token stored in the database, sent in an Authorization: Bearer header, meant for third-party clients, mobile apps, or machine-to-machine integrations that have no notion of a browser session.
  2. SPA cookie authentication: no token at all on the client side, just Laravel's classic session cookie, protected by the standard CSRF middleware. Meant for a frontend that shares the same root domain as the API (or an explicitly configured subdomain).

The choice between the two isn't a matter of preference, it's an architectural decision: a Next.js frontend served on a different domain from the API and also consumed by a mobile app should use tokens. A Vue/Inertia frontend served from the same Laravel app or a subdomain of the same root domain should use SPA cookies.

Configuring API tokens correctly

Installation adds the HasApiTokens trait to the User model, and the auth:sanctum middleware protects routes.

// app/Models/User.php
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
// routes/api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Creating a token should systematically restrict its capabilities through abilities, Sanctum's lightweight equivalent of OAuth scopes:

// Issues a token that can ONLY read orders, never modify them
$token = $user->createToken('mobile-app', ['orders:read']);

// On the protected route, check the ability, not just authentication
Route::get('/orders', function (Request $request) {
    if (! $request->user()->tokenCan('orders:read')) {
        abort(403);
    }
    // ...
})->middleware('auth:sanctum');

A common trap: issuing every token with ['*'] by default, which defeats the purpose of abilities entirely and turns every token into full account access, including tokens meant for a third-party integration that should only ever have read access.

Revocation, often forgotten until the incident happens

A Sanctum token doesn't expire by default: it stays valid until explicitly deleted. That's a meaningful difference from a classic JWT, which expires automatically. Not planning a revocation mechanism from the start means that, the day a device gets stolen or an employee leaves the company, there's no quick way to cut access other than revoking all of that user's tokens.

// Revoke one specific token (e.g. log out from a single device)
$request->user()->currentAccessToken()->delete();

// Revoke every token for the user (e.g. password change,
// suspected compromise)
$user->tokens()->delete();

For automatic expiration, Sanctum supports it through configuration, but it isn't enabled by default:

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

Without this setting, a token "forgotten" inside a mobile app build that never gets updated stays valid indefinitely.

In SPA mode, Sanctum doesn't issue any token at all. The expected sequence is: the frontend first calls GET /sanctum/csrf-cookie to obtain an XSRF-TOKEN cookie, then every mutating request (POST/PUT/DELETE) must send its value back in the X-XSRF-TOKEN header. Most modern HTTP clients (Axios in particular) handle this automatically once withCredentials/withXSRFToken is enabled, which hides the mechanism and lets developers go without really understanding it until the day it fails in production against a domain different from the one tested locally.

// Frontend - Axios
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;

await axios.get("/sanctum/csrf-cookie"); // initializes the XSRF-TOKEN cookie
await axios.post("/login", { email, password });
// config/sanctum.php - domains treated as "stateful"
'stateful' => explode(',', env(
    'SANCTUM_STATEFUL_DOMAINS',
    'localhost,127.0.0.1,app.example.com'
)),

If the frontend's domain isn't listed in stateful, Sanctum treats the request as coming from an external origin and refuses to create the session, even if CORS is otherwise configured correctly. This is the most common production misconfiguration: the stateful list gets set up for local development (localhost) and never updated with the actual production subdomain.

CORS and cookies: the combination that fails silently

SPA cookie authentication requires CORS to explicitly allow credentials, which rules out using a wildcard origin (see the dedicated CORS article for the full mechanism):

// config/cors.php
'supports_credentials' => true,
'allowed_origins' => ['https://app.example.com'], // never '*' here

Without supports_credentials: true, the browser does receive a response, but it never stores the session cookie, which produces a confusing behavior: login appears to succeed (status 200), but every subsequent request comes back unauthenticated, because the cookie was never actually saved.

The mistake to never make: mixing both mechanisms within one flow

A real architectural trap is authenticating login through an SPA cookie, then trying to read $request->user() in a context where only a Bearer token is expected (a webhook, a queued job replaying a request). The two mechanisms aren't interchangeable within the same flow: a session cookie makes no sense for a server-to-server call, and a Bearer token makes no sense for a browser that has to handle CSRF.

When Sanctum isn't enough

Sanctum is deliberately minimal: no standard OAuth scopes interoperable with external third-party clients, no delegated authorization flow (user consent for a third-party app), no OAuth2-style refresh tokens. For an API that needs to expose a real OAuth2 flow to external partners (a "Sign in with..." offered by other applications), Laravel Passport or a dedicated OAuth2 provider remains the right choice. Sanctum solves "my own frontend and my own mobile apps authenticate against my API," not "third-party applications authenticate on behalf of my users."

Where to store the token client-side, and why it matters

Choosing Sanctum with Bearer tokens shifts part of the security responsibility onto the client: unlike an SPA cookie, which can be marked HttpOnly and therefore stay invisible to JavaScript, a Bearer token has to be read by client-side code to be placed in the Authorization header, which exposes it by construction to any XSS vulnerability in the application.

Storing that token in localStorage is the most common mistake: any script injected through an XSS flaw can read and exfiltrate it, without even needing to bypass CSRF protection since it isn't a cookie at all. For a mobile application (Flutter, React Native), the token should be stored in the platform's native keychain/keystore (flutter_secure_storage, expo-secure-store), never in unencrypted key-value storage accessible to any process with the app's filesystem permissions.

// Flutter - correctly storing a Sanctum token on mobile
final storage = FlutterSecureStorage();
await storage.write(key: 'sanctum_token', value: token);

For a web SPA that still has to use tokens (a frontend on a completely separate domain from the API, incompatible with cookie mode), the least bad compromise is keeping the token in JavaScript memory (a module-level variable, an application store) rather than localStorage, at the cost of having to re-authenticate the user on every full page reload.

Rate limiting and auditing token usage

Sanctum's token model doesn't include built-in rate limiting per token; that still has to be layered on through Laravel's own throttle middleware, scoped by token or by user rather than just by IP, otherwise a single compromised token can hammer the API at the same rate as every other client combined.

// routes/api.php
Route::middleware(['auth:sanctum', 'throttle:api-user'])->group(function () {
    Route::get('/orders', [OrderController::class, 'index']);
});
// app/Providers/AppServiceProvider.php
RateLimiter::for('api-user', function (Request $request) {
    return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});

Pairing this with a last_used_at check on the token (Sanctum updates it automatically on every authenticated request) makes it possible to detect and revoke tokens that suddenly show activity from an unexpected pattern, rather than relying solely on the user to notice and report suspicious behavior.

Takeaway: choose between Bearer tokens and SPA cookies based on the frontend's actual architecture, never by default. Systematically restrict token abilities instead of relying on ['*'], and check SANCTUM_STATEFUL_DOMAINS and supports_credentials first whenever SPA authentication works locally but fails in production.