Ad

React To Laravel Csrf Token Mismatch Error Not Working Even After Trying Lot

- 1 answer

i have tried following things . but still csrf issue persists when sedning post request from react to laravel

i have used barryvh middleware cors to fixed cors issue

in 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. meta tags in page

       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. meta tag in root (index.html)

  3. tried following commented code in 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
                    },
    
  4. laravel side -- route.api.php

       // Route::middleware('auth:api')->post('/test', function (Request $request) {
       //     return response()->json(['message' =>'corstest'], 200);
       // });
       // Route::post('test', '[email protected]');
      // Route::get('test', '[email protected]');
    

how can i identity the root cause .?please suggest

Ad

Answer

Since you are using laravel as an api, using CSRF token doesn't make sense.

By default, when you use the route file routes/api.php there is no CSRF token verification in place. You can verify that in 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',
    ],
];

For The route you're calling, routes declared in routes/api.php have a prefix by default, you can check that in 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
}
Ad
source: stackoverflow.com
Ad