With Laravel Sanctum, we have to set the SANCTUM_STATEFUL_DOMAINS
environment variable to specify which domains should be treated as stateful—meaning they rely on sessions and cookies for authentication. Consequently, requests from domains not listed are treated as stateless and do not use these authentication mechanisms, which should theoretically make CSRF attacks irrelevant.
My question is: Why does Laravel still use a CSRF token in this context? Isn’t the stateful mechanism defined by SANCTUM_STATEFUL_DOMAINS
sufficient to protect against CSRF attacks ?
Laravel still requires a CSRF token even when using Sanctum with SANCTUM_STATEFUL_DOMAINS
because stateful authentication alone does not inherently prevent CSRF attacks.
While SANCTUM_STATEFUL_DOMAINS
ensures that only listed domains use session-based authentication, it does not stop a malicious site from making authenticated requests on behalf of an already logged-in user. CSRF attacks exploit the fact that browsers automatically send cookies with requests, regardless of the origin.
The CSRF token serves as an additional layer of security by ensuring that every state-changing request includes a unique, verifiable token that must be explicitly set by JavaScript running on the legitimate site. This prevents unauthorized third-party websites from forging authenticated requests, even if they originate from a domain listed in SANCTUM_STATEFUL_DOMAINS
.