创建每个新的 csrf 令牌 laravel api 路由器 axios 帖子

问题描述 投票:0回答:1

我正在从事 Laravel/Vue 项目。 我有一些带有 crsf 令牌的 axios 帖子。 但是当我将 SESSION_DRIVER 设置为

cookie
时,我得到了
419 error
,这些 axios 帖子的 CSRF 令牌不匹配。 SESSION_DRIVER 是
redis
file
,这运行良好。

客户端发送一个 csrf 令牌

if(!window.axios) {
    window.axios = require("axios");

    window.axios.defaults.headers.common = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')
    };
}
axios
    .post("/api/shopping/getCartInfo", {
        cartid: self.cartid,
    })
    .then(function (response) {
        self.cartQuantity = response.data.cart.qty;
    })
    .catch(function (error) {
                    
    });

但是每个 post 请求的后端都会收到不同的令牌。 所以会出现419错误。

public function getCartInfo(Request $request)
{
    \Log::info($request->session()->token()); // not same csrf token from client
    try {
        $cart = Cart::find($request->cartid);

        return response()->json(['result' => 'success', 'cart' => $cart]);
    } catch (\Exception $e) {
        return response()->json(['result' => 'failed', 'error' => $e->getMessage()]);
    }
}

问题是每次发布请求都会收到不同的令牌。 谁能帮我? 谢谢。

我尝试使用 csrf 令牌进行 axios post 请求,我想正常工作。

laravel redis axios token csrf
1个回答
0
投票

您是否检查过

config\cors.php
文件中的“path”和“allowed_origins”值是否设置正确?

它的内容应该是这样的:

   'paths' => [
      'api/*',
      'login',
      'logout',
      'register',
      'user/password',
      'forgot-password',
      'reset-password',
      'sanctum/csrf-cookie',
      'user/profile-information',
      'email/verification-notification',
   ],

    'allowed_methods' => ['*'],
    'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
© www.soinside.com 2019 - 2024. All rights reserved.