csrf_token() is empty in l5-swagger and couldn't do any request except GET request

Viewed 2732

csrf_token() is empty in l5-swagger and couldn't do any request except GET because the header is missing and always getting 419 error code

I have tried to request it from postman and it works. but in swagger it didn't. I have taken a look from this link (laravel 5 csrf_token value is Empty) but I still have no idea how to solve my problem.

How can I get the csrf_token inside my l5-swagger view?

3 Answers

I think you should try to add this in /routes/web.php

Route::group(['middleware' => 'web'], function () {
    Route::get('api/documentation', '\L5Swagger\Http\Controllers\SwaggerController@api')->name('l5swagger.api');
});

so you can add the web middleware on l5-swagger route

hope it helps

For Laravel 8.x the solution with Routes did not work for me.

Instead i modified the file config/l5-swagger.php

you have to add multiple entries to defaults[routes][middleware][api]. By default this entry should be empty.

To fix the CSRF-Validation you have to add:

...

'api' => [
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

...

After that just clear the config cache with

php artisan config:cache

And you are good to go!

None of these worked for me in Laravel 8.70.1.

What worked for me was to disable the EnsureFrontendRequestsAreStateful::class in both my local and dev (no public access) environments. Then in my deployment process (TeamCity & OctoDeploy) to both staging and production, the commented EnsureFrontendRequestsAreStateful::class is uncommented.

Swagger is disabled as part of the deployment process to both the staging and prod environments. If you are building a SPA you need the EnsureFrontendRequestsAreStateful class.

In summary, disabling the EnsureFrontendRequestsAreStateful::class should solve the problem, but make sure you put it back in both your staging and production environments.

File to edit is in /app/Http/Kernel.php

   //\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\AuthGates::class,


        ],
Related