CSRF Protection
Overview
Since the CPR backend is primarily a token-based API, CSRF protection works differently than traditional Laravel web applications.
How It Works
API Requests (Token Auth)
API requests authenticated via Bearer tokens are not subject to CSRF verification. The token itself serves as proof of authenticity.
GET /api/v1/patients
Authorization: Bearer 1|abc123...SPA / Cookie-Based Requests
When using Sanctum's stateful authentication (cookie-based, for the SPA frontend), CSRF protection is required:
- The SPA first requests a CSRF cookie:http
GET /sanctum/csrf-cookie - Laravel sets an
XSRF-TOKENcookie - The SPA includes this token in subsequent requests via the
X-XSRF-TOKENheader
Sanctum Middleware
Sanctum's middleware handles both authentication modes:
- Token requests (
Authorization: Bearer ...) → Skip CSRF - Cookie requests (from stateful domains) → Enforce CSRF
Configuration
Stateful Domains (config/sanctum.php)
Only requests from these domains use cookie/session authentication and require CSRF:
'stateful' => [
'localhost',
'localhost:3000',
'127.0.0.1',
'127.0.0.1:8000',
],CORS Configuration
CSRF cookies require supports_credentials: true:
// config/cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'supports_credentials' => true,Frontend Integration
If using cookie-based auth from the SPA:
// First, get the CSRF cookie
await fetch('/sanctum/csrf-cookie', { credentials: 'include' });
// Then make authenticated requests
await fetch('/api/v1/patients', {
credentials: 'include',
headers: {
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
},
});TIP
For most API interactions, the CPR frontend uses token-based auth (Bearer tokens), which does not require CSRF handling. CSRF is only relevant for the stateful/cookie authentication mode.