DEV Community

Discussion on: Laravel Sanctum Explained : SPA Authentication

Collapse
 
emekambah profile image
Emeka Mbah

Nice tutorial.
I have a Vue SPA on windows frontend.mydomain.test/ and Backend laravel API on Ubuntu server backend.mydomain.test/.

I have these in .env file

SESSION_DOMAIN=mydomain.test
SANCTUM_STATEFUL_DOMAINS=frontend.mydomain.test

I have also configured core and Sanctum middleware.

config/cors.php

 'paths' => [
        'api/*',
        'graphql',
        '/login',
        '/logout',
        '/sanctum/csrf-cookie'
    ],
``

On a request attempt to  http://backend.mydomain.test/sanctum/csrf-cookie, I receive the error message below. What am I missing?

Access to XMLHttpRequest at 'backend.mydomain.test/sanctum/csrf...' from origin 'frontend.mydomain.test:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.



Collapse
 
nicolus profile image
Nicolas Bailly

Hi !

Your session domain should be

SESSION_DOMAIN=.mydomain.test

With a . in front of the domain, so that it can be accessed by both the frontend and the backend.

However I doubt that's what is causing your issue with CORS. Make sure the front-end domain is listed in the 'allowed_origins' part of the cors.php config file (or that it's set to ['*']). The paths looks OK, but just in case you could try to replace them with ['*'] too just to make sure there isn't something funky going on there.

Also make sure you have

'supports_credentials' => true

in cors.php.

If none of that helps, have a look at the 'OPTIONS' request in the developer tools of your browser, and check if it returns successfully and if it has the required headers (Access-Control-Allow-Origin etc.) . Sometimes it looks like CORS is failing when really it's a completely unrelated error that makes your app crash with an 500 error before it could send the correct headers.