Nee*_*rma 1 php laravel csrf-token
我尝试过以下事情。但当 sedning post 请求从 React 发送到 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,
Run Code Online (Sandbox Code Playgroud)
页面中的元标记
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() }*/}
Run Code Online (Sandbox Code Playgroud)根目录中的元标记 (index.html)
尝试遵循帖子中的注释代码
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
},
Run Code Online (Sandbox Code Playgroud)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');
Run Code Online (Sandbox Code Playgroud)我怎样才能确定根本原因?请提出建议
由于您使用 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',
],
];
Run Code Online (Sandbox Code Playgroud)
对于您正在调用的路由,默认情况下声明的路由有一个前缀,您可以在@routes/api.php中检查:app\Providers\RouteServiceProvider.phpmapApiRoutes
/**
* 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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12378 次 |
| 最近记录: |