0

I have a SPA app where I try to implement Sanctum's CSRF protection.

From docs:

To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application

Right now I request CSRF token before I login

axios.get('/sanctum/csrf-cookie').then(response => {
   // Login...
});

Should I request CSRF token before doing ANY post request in my application? If yes, I basically need to request a CSRF token before routes like POST api/password_reset, POST api/tracking, POST api/register etc.

Or is there any way to tell Laravel Sanctum to only return 419 CSRF token mismatch errors for protected routes, ie. routes with auth:sanctum middleware?

EDIT:

Just wanted to make it clear that I don't have an issue with CSRF implementation in general. It works great after I have requested the CSRF token. Axios will add the token in all subsequent requests. My question is really about when to do the first request to CSRF token.

Toydor
  • 2,277
  • 4
  • 30
  • 48
  • 1
    Does this answer your question? [Laravel 7 Vue 2 Sanctum Login Error 419; CSRF Token Mismatch](https://stackoverflow.com/questions/63527334/laravel-7-vue-2-sanctum-login-error-419-csrf-token-mismatch) – Bhavin Solanki Feb 15 '21 at 07:04
  • @BhavinSolanki No that doesn't help unfortunately. I edited my question. – Toydor Feb 15 '21 at 07:24

1 Answers1

1

I have searched for something similar and I stumbled upon this; Laravel: How to Avoid TokenMismatchException CSRF Token on certain routes using a method

You can therefore kindly exclude the routes from being checked for CSRF token by adding the route path in $except array in VerifyCsrfToken class inside the app/Http/Middleware/VerifyCsrfToken.php like shown below;

protected $except = [
    '/api/password_reset',
    '/api/tracking',
    '/api/register',
];

This can be seen also in Laravel Official Documentation Excluding URIs From CSRF Protection