dystcz / nuxt-sanctum-auth

Nuxt 3 + laravel sanctum authentication
135 stars 25 forks source link

CORS error #36

Closed Steentoft closed 1 year ago

Steentoft commented 1 year ago

I've been trying to deploy my laravel 9 backend and nuxt 3 frontend for some time now, but I keep getting CORS errors.

Here is my setup:

 `APP_URL=https://api.mydomain.com
FRONTEND_URL=https://mydomain.com

SANCTUM_STATEFUL_DOMAINS=.mydomain.com
SESSION_DOMAIN=.mydomain.com`

cors.php

 'paths' => ['*', 'api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['https://mydomain.com'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true

I have read a lot of similar issues on here, but nothing seems to fix the problem.

kreejzak commented 1 year ago

Hi, maybe @theimerj could help?

theimerj commented 1 year ago

Hey @Steentoft, I will start by sharing our config, which works well.

  nuxtSanctumAuth: {
    baseUrl: process.env.API_AUTH_URL,
    redirects: {
      home: '/account',
      login: '/auth/login',
      logout: '/'
    }
  },

where process.env.API_AUTH_URL is the base domain: localhost:8000 on local for example and then api.example.com

on the backend we have this in our .env:

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=.example.com
SANCTUM_STATEFUL_DOMAINS=example.com

you can try experimenting with "opening" the CORS settings first, just so to make it working and then limit the access:

return [

    'paths' => ['*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

I would really recommend to read the sanctum documentation carefully, because tiny divergence in your config can cause problems.

One more thing: Laravel sometimes returns "CORS errors" when your backend returns 500, so check your logs carefully and try to find the problem there.

I hope you will resolve your issue.

Steentoft commented 1 year ago

I seem to have fixed the issue.

I'm not completely sure what the error was or if my setup were already right to begin with. But when i ran:

php artisan config:clear
php artisan route:clear
php artisan cache:clear

Everything seemed to work.

I think I haven't used laravel enough to have had any problems with cache, but clearing it seems to have fixed the issue.

Thanks for the help though it is very appreciated.