簡體   English   中英

對 laravel csrf 令牌不匹配錯誤做出反應,即使在嘗試了很多之后也不起作用

[英]react to laravel csrf token mismatch error not working even after trying lot

我已經嘗試過以下事情。 但是當從反應到 laravel 的 sedning 發布請求時仍然存在 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,
  1. 頁面中的元標記

     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() }*/}
  2. 根中的元標記 (index.html)

  3. 嘗試在帖子中遵循注釋代碼

     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 },
  4. 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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM