首页 > 解决方案 > Laravel 7 Vue 2 Sanctum 登录错误 419;CSRF 令牌不匹配

问题描述

我正在使用 Laravel 与 Vue 的默认集成(不是使用 Vue CLI 的单独项目)。我正在尝试对用户进行身份验证,但它总是显示 419 错误。我已将 csrf 令牌包含到 Axios 的标头中,但它仍然提供不匹配错误。

引导程序.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
window.axios.defaults.baseURL = "http://localhost:8000/";
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');

内核.php

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
]

cors.php

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

网页.php

Route::get('/{any?}', function() {
    return view('welcome');
});

Route::post('/login', 'AuthController@login');
Route::post('/logout', 'AuthController@logout');

登录模式.vue

<template>
    <form @submit.prevent="submit" method="POST">
        <input type="text" class="form-control" placeholder="Email" v-model="email" />
        <input
            type="password"
            class="form-control"
            placeholder="Password"
            v-model="password"
        />

        <button>SIGN IN</button>
    </form>
</template>

<script>
import { mapActions } from 'vuex'

export default {
    data() {
        return {
            email: '',
            password: '',
        }
    },
    methods: {
        ...mapActions('user', ['login']),
        async submit() {
            await this.login({
                email: this.email,
                password: this.password,
            })

            this.$router.replace({ name: 'Topic' })
        },
    },
}
</script>

用户.js | Vuex 模块

async login({ dispatch }, credentials) {
    await axios.get('/sanctum/csrf-cookie')
    await axios.post('/login', credentials)

    return dispatch('me')
},

我正在配置与本文类似的项目。他是一个单独的项目,而我在 Laravel 项目中。我还参考了 Laravel 关于配置身份验证的 sanctum 文档,但它仍然不起作用。回顾了很多 StackOverflow 问答,到目前为止还没有运气。大多数人都在谈论向 Axios 添加 CSRF 标头,我已经在 bootstrap.js. 我确实尝试包括一个隐藏的输入来保存 CSRf,但仍然没有运气。

标签: laravelvue.jssingle-page-applicationcsrflaravel-sanctum

解决方案


你记得检查你的config/session.php域吗?

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */
    'domain' => env('SESSION_DOMAIN', null),

然后 .env 中的 SESSION_DOMAIN 应该是.localhost

另外,你记得检查config/sanctum.php有状态吗?

    /*
    |--------------------------------------------------------------------------
    | Stateful Domains
    |--------------------------------------------------------------------------
    |
    | Requests from the following domains / hosts will receive stateful API
    | authentication cookies. Typically, these should include your local
    | and production domains which access your API via a frontend SPA.
    |
    */
    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),

.env 中的 SANCTUM_STATEFUL_DOMAINS 是localhost,127.0.0.1


推荐阅读