Sanctum for SPAs

Sanctum SPA and Mobile Authentication

A first-party SPA should not hold a token, since any script injected through XSS can read localStorage. Sanctum 2,988 lets it use the session cookie instead. $middleware->statefulApi() adds EnsureFrontendRequestsAreStateful to the api group, which starts a session and enforces CSRF for requests whose Origin or Referer is listed in SANCTUM_STATEFUL_DOMAINS. The SPA first calls /sanctum/csrf-cookie, which answered 204 No Content with XSRF-TOKEN and laravel-session cookies. It then posts to /login (Fortify 1,761 , Fortify) with an X-XSRF-TOKEN header, which Axios 109,234 adds when withCredentials and withXSRFToken are set.

SPA and API must share a parent domain (app.example.com, api.example.com), with supports_credentials set in config/cors.php and the session domain set to .example.com.

A mobile app uses the token route of Sanctum Tokens with a recognizable device name and keeps the token in the Keychain or Android Keystore. Logging out calls currentAccessToken()->delete(). auth:sanctum tries the session, then the Authorization header, so one route serves both.