Skip to content

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.

http
GET /api/v1/patients
Authorization: Bearer 1|abc123...

When using Sanctum's stateful authentication (cookie-based, for the SPA frontend), CSRF protection is required:

  1. The SPA first requests a CSRF cookie:
    http
    GET /sanctum/csrf-cookie
  2. Laravel sets an XSRF-TOKEN cookie
  3. The SPA includes this token in subsequent requests via the X-XSRF-TOKEN header

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:

php
'stateful' => [
    'localhost',
    'localhost:3000',
    '127.0.0.1',
    '127.0.0.1:8000',
],

CORS Configuration

CSRF cookies require supports_credentials: true:

php
// config/cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'supports_credentials' => true,

Frontend Integration

If using cookie-based auth from the SPA:

javascript
// 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.

CPR - Clinical Patient Records