Nuxt项目尝试通过Laravel Sanctum登录用户时抛出CSRF令牌不匹配419错误

时间:2020-10-11 10:46:47

标签: laravel vue.js nuxt.js laravel-sanctum

项目结构:

2个文件夹,分别为apiclient,其中api用于laravel安装,客户端指的是nuxt项目。

Laravel(v-8.00)设置:

这是我在.env文件中拥有的会话变量

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=127.0.0.1
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:3000

cors.php包含以下内容

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

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => false,

'max_age' => true,

'supports_credentials' => true,

未对sanctum.php进行任何更改,其中包含

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000,::1')),

Nuxt设置

.env文件包含:

PORT=3000
HOST=127.0.0.1
BASE_URL=http://127.0.0.1:3000
API_URL=http://127.0.0.1:8000

nuxt.config.js包含:

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth-next',
    '@nuxtjs/pwa',
    '@nuxtjs/dotenv',
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
    baseUrl: process.env.API_URL,
    credentials: true,
},

auth: {
    strategies: {
    cookie: {
        cookie: {
        name: 'XSRF-TOKEN',
        }
    },
        'laravelSanctum': {
        provider: 'laravel/sanctum',
        url: process.env.API_URL
        },
    },
    redirect: {
        login: '/login',
        logout: '/login',
        callback: '/login',
        home: '/'
    }
},

Login.vue

    data() {
        return {
            form: {
                email: '',
                password: ''
            },
            errors: {}
        }
    },

    methods: {
        async submit () {
            this.$auth.loginWith('laravelSanctum', { data: this.form })
            .then(response => {
                this.$router.push(`/`)
            })
            .catch(({response}) => {
                this.errors = response.data.errors
            })

        }
    },

回复

这是我尝试登录用户时得到的响应:

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

我知道这是一个老问题。但我只是自己遇到了这个问题,并认为我会分享对我有用的东西。

显然,设置 SESSION_DOMAIN=127.0.0.1 会引发 419 错误并显示“CSRF 令牌不匹配”。

但是,如果您将其设置为 SESSION_DOMAIN=localhost,则效果很好。

答案 1 :(得分:0)

419 错误表示您的会话域设置不正确。 如果您使用 localhost,请在下面设置您的域 like

SESSION_DOMAIN=.localhost

删除。本地主机之前

SESSION_DOMAIN=localhost