Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lumen Enable CSRF Token

I know lumen is used to session less API development still i have a situation where i need to enable CSRF token.Session every think works fine but i need to enable csrf token if i add

<input type="hidden" name="_token" value="{{ csrf_token() }}"> 

in form i got error

(1/1) ReflectionException Class Laravel\Lumen\Http\Middleware\VerifyCsrfToken does not exist

In bootstrap/app.php i have uncommented following

$app->middleware([
      'Illuminate\Cookie\Middleware\EncryptCookies',
     'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
     'Illuminate\Session\Middleware\StartSession',
   'Illuminate\View\Middleware\ShareErrorsFromSession',
    'Laravel\Lumen\Http\Middleware\VerifyCsrfToken',
 ]);

even i have enabled

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
    'csrf' => 'Laravel\Lumen\Http\Middleware\VerifyCsrfToken'
]);

if i comment csrf in middleware then i get following error

Call to undefined function csrf_token() in blade

I am using laravel "laravel/lumen-framework": "5.5.*",

can any one help me how i can enable VerifyCsrfToken in lumen

like image 988
scott Avatar asked Mar 15 '26 17:03

scott


2 Answers

Had this same issue. Posting here if someone in future.

Found out that they removed all csrf stuff from lumen since 5.2 (not exactly sure since which version). To use csrf in Lumen 5.5 or later you need to create yourself or copy VerifyCsrfToken middleware file from laravel package of that specific version (find in github) and place in lumen middleware folder and adjust the path in bootstrap/app.php accordingly.

You may need to install illuminate/cookie or other required package manually as well.

VerifyCsrfToken.php file can be found at laravel/framework/src/illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php

like image 87
cjmling Avatar answered Mar 17 '26 06:03

cjmling


From the lumen documentation Validation

Form Requests

Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.

The Lumen microframework v5.8 don't support form, so it don't have csrf

like image 44
europrimus Avatar answered Mar 17 '26 06:03

europrimus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!