XSRF-TOKEN token sent still getting 419 (CSRF token mismatch) using Laravel Sanctum

111 Views Asked by At

I am building a Laravel10+Vue3 SPA. I initialized my laravel application using Laravel Breeze (only API portion) starter kit. I didn't change any default configuration of it in any places (e.g. config/cors.php, config/sanctum.php, config/session.php, etc.). Just I did two obvious changes in my .env file:

...
APP_URL=http://localhost:8000
FRONTEND_URL=http://localhost:5173
...

On localhost, everything works fine without any issue. But, when I deploy it to a shared hosting, it's getting issues! To understand the context, I am keeping my backend into a subfolder called laravel-breeze-api and frontend into a subfolder called frontend. The changes in the .env file are as follows:

...
APP_URL=http://tiny-url-builder.c1.is/laravel-breeze-api
FRONTEND_URL=http://tiny-url-builder.c1.is/frontend
...

When I test the API from postman, it works without any issue.

enter image description here

But, when I test from the browser, I am constantly getting 419 (proxy reauthentication required).

enter image description here

I am correctly calling sanctum/csrf-cookie before calling the login endpoint and it correctly saves the necessary cookies.

enter image description here

On the /login api call the request headers are also containing those values, but I am getting CSRF token mismatch constantly.

enter image description here

Kindly assist me to understand what I am doing wrong. Thanks so much!

1

There are 1 best solutions below

0
Mohammad Salah On

I have investigated the problem in more depth and found a simple solution. If I look into my config/sanctum.php file, I do see:

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : '',
        env('FRONTEND_URL') ? ',' . parse_url(env('FRONTEND_URL'), PHP_URL_HOST) : ''
    )
)),

So, I expected the SANCTUM_STATEFUL_DOMAINS would be filled properly as it is also adding my FRONTEND_URL from .env file. What I didn't notice is that: parse_url method is being used with the second parameter PHP_URL_HOST. So, the actual value which was getting set was tiny-url-builder.c1.is (without URL scheme).

It wouldn't work in the shared hosting environment I was dealing with. So, the simple solution I found is to add an extra .env variable SANCTUM_STATEFUL_DOMAINS and set its value to either localhost or http://tiny-url-builder.c1.is (with URL scheme).