使用laravel-cors和axios的POST的Laravel"CSRF令牌不匹配" [英] Laravel “CSRF token mismatch” for POST with laravel-cors and axios
问题描述
我有一个运行 Laravel 5.8 引擎的domain_A,可以在网络路由上返回API.它必须检查来源,以便仅提供包括domain_B在内的几个域.
I have a domain_A running Laravel 5.8 engine to return API on web route. It must check origins to let serve just a few domains, included domain_B.
Barryvdh/laravel-cors
我通过作曲家安装了 barryvdh/laravel-cors ,并对其进行了全局配置以更新Kernel.php.这也应该适用于网络路由.
Barryvdh/laravel-cors
I installed barryvdh/laravel-cors by composer and configured it globally updating the Kernel.php. This should works on web route too.
kernel.php
protected $middleware = [
...
\Barryvdh\Cors\HandleCors::class,
];
然后,我使用标准配置作为测试来配置 Laravel Cors ,以允许任何域.
Then I config the Laravel Cors using the standard configuration as test to allow any domain.
/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'=> ['*'],所以它应该可以工作...我所缺少的是什么?
GET requests are filtered as well, PUT request return a 419 error why? I have set 'allowedMethods' => ['*'] so it should work... what I'm missing?
[ EDIT ]
在调试时,我现在收到此错误...
ON debug I got this error right now...
消息:"CSRF令牌不匹配."
message: "CSRF token mismatch."
为什么POST无法获取标头令牌?
Why POST doesn't get the header Token?
我也尝试像这样传递POST令牌:
I tried to pass the POST token also like this:
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请求相同.
Note about token: It should be OK because it is the same as another GET request done in the same task.
推荐答案
请使用route/api.php进行api路由,不要将路线/web.php用于api.
Please use routes/api.php for apis routing, don't use the routes/web.php for api.
如果要使用子域,请在以下文件中进行必要的更改:
If you want to use sub-domain then do required changes in following file:
app/Providers/RouteServiceProvider.php
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'));
}
这篇关于使用laravel-cors和axios的POST的Laravel"CSRF令牌不匹配"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!