Nuxt-Laravel-Sanctum CSRF令牌不匹配419错误

Nuxt-Laravel-Sanctum CSRF token mismatch 419 error

我有一个 Nuxt-Laravel-Sanctum CSRF 令牌不匹配 419 错误,而 Laravel 托管在服务器上,而 Nuxt 在 PC 的本地主机上。我已经上传了我的 Laravel 项目以在 api.repairtofix.com.

上获得 API

我正在尝试从 localhost 在我的电脑上从 Nuxt 登录。单击登录按钮时出现以下错误。

{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}

登录方式

login() {
    this.$auth.loginWith('laravelSanctum', { 
        data: this.form 
    })
    .then(response => console.log(response))
    .catch(error => console.log(response))
}

.env

APP_URL=http://api.repairtofix.com
SESSION_DOMAIN=api.repairtofix.com
SANCTUM_STATEFUL_DOMAINS=.repairtofix.com,localhost:3000

Kernel.php

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

sanctum.php

'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 
    'api.repairtofix.com,localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'
)),

cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'signup', 'getUser'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

api.php

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

// register
Route::get('register', function(Request $request){
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);

    return $user;
});

// login
Route::post('login', function(Request $request){
    $credentials = $request->only('email', 'password');
    if(!auth()->attempt($credentials)){
        throw ValidationException::withMessages([
            'email' => 'Invalid credentials'
        ]);
    }

    $request->session()->regenerate();
    return response()->json(null, 201);
});

// logout
Route::post('logout', function(Request $request){
    auth()->guard('web')->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return response()->json(null, 201);
});

nuxt.config.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth-next',
    '@nuxtjs/toast',
],

auth:{
    strategies: {
        'laravelSanctum': {
            provider: 'laravel/sanctum',
            url: 'http://api.repairtofix.com',
            endpoints: {
                login: {
                    url: '/api/login'
                },
                logout: {
                    url: '/api/logout'
                },
                user: {
                    url: '/api/user'
                },
            },
            user: {
                property: false
            }
        },
    },
    redirect: {
        login: "/login",
        logout: "/",
        home: "/"
    }
},

我猜你在 sanctum 中使用 SPA 身份验证,你的服务器和客户端必须在同一个域中。客户端 (localhost) 和您的 api 在不同的域中。

docs

In order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains.

在我的例子中,Axios 凭据在 nuxt.config 文件中未设置为 true,而且文本区分大小写


  axios: {
    baseUrl: 'http://localhost:8000',
    credentials: true,
  },

可能有点晚了,但其他人会在以后。 1-检查 laravel 中的 api/config/sanctum 并使 localhost:xxxx 和 127.0.0.1:xxxx 上的端口正确 2-on .env 文件对 SANCTUM_STATEFUL_DOMAINS=localhost:xxxx

进行协调