对 laravel csrf 令牌不匹配错误做出反应,即使在尝试很多之后也无法正常工作
react to laravel csrf token mismatch error not working even after trying lot
我尝试了以下操作。但当 sedning post 请求对 laravel
做出反应时,csrf 问题仍然存在
我已经使用 barryvh 中间件 cors 来修复 cors 问题
在cors.php
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With','token','user_token','_token','X-CSRF-TOKEN'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
页面中的元标记
return (
<div className="Login" style={{fontFamily: 'Montserrat, sans-serif',height:'36em'}}>
<input type="hidden" name="_token" value="{{ csrf_token() }}"></input>
<meta name="csrf-token" content="{{ csrf_token() }}"/>
{/* { csrf_token() } */}
{/* { @csrf } */}
{/* { csrf_field() }*/}
根中的元标记 (index.html)
尝试按照 post
中的注释代码
return fetch("www.campaignserver.com:3001/test",
{
method: 'post',
credentials: "same-origin",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//"_token": "{{ csrf_token() }}",
"X-Requested-With": "XMLHttpRequest",
'X-CSRF-TOKEN': document.querySelector("[name~=csrf-token]
[content]").content
},
laravel边--route.api.php
// Route::middleware('auth:api')->post('/test', function (Request $request) {
// return response()->json(['message' =>'corstest'], 200);
// });
// Route::post('test', 'HomeController@test');
// Route::get('test', 'HomeController@test');
我如何确定根本原因?请提出建议
由于您将 laravel 用作 api,因此使用 CSRF 令牌没有意义。
默认情况下,当您使用路由文件时routes/api.php
,没有适当的 CSRF 令牌验证。您可以在 app/Http/Kernel.php
:
中验证
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class, //<-- HERE IS THE CSRF VERIFICATION
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [ //<--- AS you can see there is no VerifyCsrfToken middleware in API
\Barryvdh\Cors\HandleCors::class,
'throttle:300,1',
'bindings',
],
];
对于你调用的路由,在routes/api.php
中声明的路由默认有一个前缀,你可以在app\Providers\RouteServiceProvider.php
中查看@mapApiRoutes
:
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api') //<-- here is the prefix
->middleware('api') //<-- this is the kernel middleware used for this route group
->namespace($this->namespace)
->group(base_path('routes/api.php')); //<-- and here is the related file
}
我尝试了以下操作。但当 sedning post 请求对 laravel
做出反应时,csrf 问题仍然存在我已经使用 barryvh 中间件 cors 来修复 cors 问题
在cors.php
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With','token','user_token','_token','X-CSRF-TOKEN'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
页面中的元标记
return ( <div className="Login" style={{fontFamily: 'Montserrat, sans-serif',height:'36em'}}> <input type="hidden" name="_token" value="{{ csrf_token() }}"></input> <meta name="csrf-token" content="{{ csrf_token() }}"/> {/* { csrf_token() } */} {/* { @csrf } */} {/* { csrf_field() }*/}
根中的元标记 (index.html)
尝试按照 post
中的注释代码return fetch("www.campaignserver.com:3001/test", { method: 'post', credentials: "same-origin", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', //"_token": "{{ csrf_token() }}", "X-Requested-With": "XMLHttpRequest", 'X-CSRF-TOKEN': document.querySelector("[name~=csrf-token] [content]").content },
laravel边--route.api.php
// Route::middleware('auth:api')->post('/test', function (Request $request) { // return response()->json(['message' =>'corstest'], 200); // }); // Route::post('test', 'HomeController@test'); // Route::get('test', 'HomeController@test');
我如何确定根本原因?请提出建议
由于您将 laravel 用作 api,因此使用 CSRF 令牌没有意义。
默认情况下,当您使用路由文件时routes/api.php
,没有适当的 CSRF 令牌验证。您可以在 app/Http/Kernel.php
:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class, //<-- HERE IS THE CSRF VERIFICATION
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [ //<--- AS you can see there is no VerifyCsrfToken middleware in API
\Barryvdh\Cors\HandleCors::class,
'throttle:300,1',
'bindings',
],
];
对于你调用的路由,在routes/api.php
中声明的路由默认有一个前缀,你可以在app\Providers\RouteServiceProvider.php
中查看@mapApiRoutes
:
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api') //<-- here is the prefix
->middleware('api') //<-- this is the kernel middleware used for this route group
->namespace($this->namespace)
->group(base_path('routes/api.php')); //<-- and here is the related file
}