使用laravel-cors和axios的POST的Laravel“ CSRF令牌不匹配”

时间:2019-06-30 11:59:44

标签: laravel vue.js cors axios csrf

我有一个运行 Laravel 5.8 引擎的domain_A,可以通过网络路由返回API。它必须检查来源,以便仅服务于包括domain_B在内的几个域。

Barryvdh / laravel-cors
我由作曲者安装了barryvdh/laravel-cors并将其配置为全局更新Kernel.php。这也应该适用于网络路由。

kernel.php

protected $middleware = [
   ...
  \Barryvdh\Cors\HandleCors::class,
];

然后我使用标准配置作为测试来配置 Laravel Cors ,以允许任何域。

/config/cors.php

 return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['http:www.domain_b.com','https:www.domain_b.com','http:domain_b.com'],
    'allowedHeaders' => ['Access-Control-Allow-Origin', 'X-CSRF-TOKEN', 'Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
];

axios配置为:

(domain_a)/ Repository.js

import axios from 'axios/index';

const baseDomain = "https://domain_a";
const baseURL = `${baseDomain}`;

let withCredentials = false;

const token = document.head.querySelector('meta[name="csrf-token"]');

const headers = {
   'X-CSRF-TOKEN': token.content,
   'Access-Control-Allow-Origin': '*',
   'X-Requested-With': 'XMLHttpRequest',
   'Content-Type': 'application/json',
};


export default axios.create({
    baseURL,
    withCredentials: withCredentials,
    headers: headers
});

GET请求也被过滤,PUT请求为什么返回419错误?我已经设置了'allowedMethods'=> ['*'],所以它应该可以工作...我所缺少的是什么?

[ EDIT ]

在调试时,我现在收到此错误...

  

消息:“ CSRF令牌不匹配。”

为什么POST无法获取标头令牌?

我也尝试像这样传递POST令牌:

 const token = document.head.querySelector('meta[name="csrf-token"]');
const options = {
    headers: {
        'Authorization' :  'bearer '+token.content,
    }
};
const body = {};
return Repository.post(`${resource}/${$playerId}/${$cozzaloID}`, body, options)

Preflight标头响应

 Access-Control-Allow-Headers: authorization, content-type, x-requested-with, x-csrf-token
 Access-Control-Allow-Methods: POST
 Access-Control-Allow-Origin: http://www.******.**
 Cache-Control: no-cache, private
 Connection: Keep-Alive
 Content-Length: 0
 Content-Type: text/html; charset=UTF-8
 Date: Mon, 01 Jul 2019 05:14:22 GMT
 Keep-Alive: timeout=5, max=98
 Server: Apache
 X-Powered-By: PHP/7.1.30, PleskLin

标题响应

Access-Control-Allow-Origin: http://www.xxxxxxx.xx
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Type: application/json
Date: Mon, 01 Jul 2019 05:14:22 GMT
Keep-Alive: timeout=5, max=97
Server: Apache
Transfer-Encoding: chunked
Vary: Origin,Authorization
X-Powered-By: PHP/7.1.30, PleskLin

标题请求

Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer jW6pFcVlkKyApCxtZIlfaHDPMSFWCWcbnPPTQ7EJ
Content-Type: application/json
Origin: http://www.xxxxxxx.xx 
Referer: http://www.xxxxxx.xx/players/739
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 
Safari/537.36
X-CSRF-TOKEN: jW6pFcVlkKyApCxtZIlfaHDPMSFWCWcbnPPTQ7EJ
X-Requested-With: XMLHttpRequest

关于令牌 的说明:应该可以,因为它与在同一任务中完成的另一个GET请求相同。

2 个答案:

答案 0 :(得分:2)

请使用routes / api.php进行api路由, 不要将路线/web.php用于api。

如果要使用子域,请在以下文件中进行必要的更改:

  

app / Providers / RouteServiceProvider.php

原文:

protected function mapApiRoutes() {
    Route::prefix('api')
    ->middleware('api')
    ->namespace($this->namespace)
    ->group(base_path('routes/api.php'));
}

已更新:

protected function mapApiRoutes() {
    Route::domain('api.' .  env('APP_URL'))
    ->middleware('api')
    ->namespace($this->namespace)
    ->group(base_path('routes/api.php'));
}

答案 1 :(得分:0)

在地址

vendor/fruitcake/laravel-cors/src/HandleCors.php

评论这个

        // Check if we're dealing with CORS and if we should handle it
         if (! $this->shouldRun($request)) {
         return $next($request);
          }
相关问题