redis 创建每一个新的csrf令牌laravel API路由器axios后

68bkxrlz  于 8个月前  发布在  Redis
关注(0)|答案(1)|浏览(73)

我正在做Laravel/Vue项目。我有一些axios的帖子与crsf令牌。但是当我将SESSION_DRIVER设置为cookie时,我得到了419 error,其中CSRF令牌不匹配这些axios帖子。SESSION_DRIVER是redisfile,这工作得很好。
客户端发送一个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请求的后端接收不同的token。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()]);
    }
}

问题是每次为每个post请求接收不同的令牌。谁能帮我?谢谢.
我尝试了axios post请求与csrf令牌,我想正常工作。

rryofs0p

rryofs0p1#

您是否在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,

相关问题