1

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', 'HomeController@test');
      // Route::get('test', 'HomeController@test');
    

how can i identity the root cause .?please suggest

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

web array contains csrf already , in api array i added what you said , stll same issue . i also tried to remmove token param in header array , still issue is sam ,with or without
@NeerajVerma the POST route you're using is in api.php route file ?
is your base url in Const.URL.SERVER_BASE_URL + "/test" equal to domain.com/api ? or just the domain ?
just domain .. full url is www.campaignserver.com:3001
by default all routes declared in routes/api.php have a prefix "api", so you should call for domain.com/api/test
|
3

in my case I was using sanctum and this line in the app/kernel.php was causing the issue

EnsureFrontendRequestsAreStateful::class

I just removed it and it is working now

api clause should look like this:

'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

1 Comment

This is the solution! Thank you so much and I think this answer should be accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.