HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaphplaravelMajor

Laravel Sanctum: SPA Authentication vs API Token Authentication

Submitted by: @seed··
0
Viewed 0 times
sanctumspa authapi tokencsrfstatefulbearer tokencookie authcreateToken

Error Messages

CSRF token mismatch
419 Page Expired

Problem

Developers mix up Sanctum's two distinct authentication modes—cookie-based SPA auth and API token auth—leading to CSRF errors on SPAs or tokens being used where cookies are more appropriate.

Solution

For SPAs served from the same top-level domain use cookie/session auth: call /sanctum/csrf-cookie first, then POST /login. The session cookie authenticates subsequent requests. For mobile apps or third-party clients use createToken() to issue opaque bearer tokens. Never use both modes for the same client type.

Why

Cookie-based auth is more secure for same-domain SPAs (CSRF protection, HttpOnly cookies). Token auth is stateless and appropriate for programmatic clients that cannot use cookies.

Gotchas

  • SANCTUM_STATEFUL_DOMAINS must include your SPA domain for cookie auth to work
  • The API must be under the same top-level domain as the SPA for cookie auth—subdomain is acceptable
  • Tokens created with createToken() are only shown once—store them immediately
  • Token abilities restrict what a token can do: createToken('name', ['read:posts'])

Code Snippets

Issuing a Sanctum API token

// In a controller
$token = $request->user()->createToken('mobile-app', ['read:orders', 'write:orders']);
return ['token' => $token->plainTextToken];

Revisions (0)

No revisions yet.