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

Laravel “CSRF token mismatch” for POST with laravel-cors and axios

我有一个 domain_A 运行 Laravel 5.8 引擎到 return API 网络路线。它必须检查来源以仅服务于几个域,包括 domain_B.

Barryvdh/laravel-cors
我通过 composer 安装了 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 请求return 出现 419 错误,为什么?我已经设置 'allowedMethods' => ['*'] 所以它应该可以工作...我缺少什么?

[编辑]

在调试时我现在遇到这个错误...

message: "CSRF token mismatch."

为什么 POST 没有得到 header 令牌?

我也试过像这样传递 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)

预检Header响应

 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

Header 响应:

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

Header 请求:

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

关于token的注意事项:应该是可以的,因为在同一个任务中完成的另一个GET请求是一样的

请使用 routes/api.php 作为 api 的路由, 不要将 routes/web.php 用于 api.

如果您想使用 sub-domain,请在以下文件中进行必要的更改:

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'));
}

在地址

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);
          }