nuxt-community / auth-module

Zero-boilerplate authentication support for Nuxt 2
https://auth.nuxtjs.org
MIT License
1.94k stars 925 forks source link

blocked by CORS policy with Laravel Sanctum provider : Proxy uncorrectly configured ? #708

Closed gilles6 closed 4 years ago

gilles6 commented 4 years ago

I have a Laravel website served by Valet on backend.test and a Nuxt SPA on nuxt.backend.test:3005. When I try to authenticate to Sanctum with Nuxt Auth module, I get the CORS error below:

Access to XMLHttpRequest at 'http://backend.test/login' from origin 'http://nuxt.backend.test:3005' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I fix it ? My guess is that the proxy is not properly configured.

Laravel configuration

config/cors.php:

<?php

return [
    'paths' => ['*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

routes/api.php:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

app/Http/Kernel.php:

    protected $middlewareGroups = [
        ...
        'api' => [
            EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

.env:

SANCTUM_STATEFUL_DOMAINS="backend.test"
SESSION_DOMAIN=".backend.test"

Nuxt configuration

nuxt.config.js:

export default {
  server: {
    port: '3005',
    host: 'nuxt.backend.test'
  },
  ...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/nuxt': {
      target: 'nuxt.backend.test',
      pathRewrite: { '^/nuxt': '/' }
    }
  },
  auth: {
    redirect: {
      callback: '/auth/callback'
    },
    strategies: {
      laravelSanctum: {
        provider: 'laravel/sanctum',
        url: 'http://backend.test'
      }
    }
  },
  ...
}

pages/index.php:

<template>
  <div>
    <div>
      <pre>{{ $auth.user }}</pre>
    </div>
    <button @click="signIn()">Sign in</button>
  </div>
</template>

<script>
export default {
  methods: {
    signIn() {
      this.$auth.loginWith('laravelSanctum', {
        data: {
          email: 'me@home.com',
          password: '1qaz@WSX'
        }
      })
    }
  }
}
</script>
aldarund commented 4 years ago

thats not a nuxt problem. You should configure your backend to return proper cors fields, please ask at the backend community that u are using