curiosity's avatar

Disable verify csrf token by middleware

Just curious, I know that it's possible to disable verify csrf tokens by adding specific routes to the VerifyCsrfToken.php $except array, but I am wondering if there's someway that it could be done by adding middleware to the routes, such as:

Route::post('my-route', ['as'=>'myRoute', 'uses'=>'MyController@index', 'middleware'=>'no_csrf']);
0 likes
8 replies
tisuchi's avatar

There are few way to solve this issue, may be. But I suggest to go- App\Http\Kernel.php

And comment this line from protected $middleware array.

                'App\Http\Middleware\VerifyCsrf',

Of course, there are few more way to go.

curiosity's avatar

Will that overwrite Laravel code on updating the version?

curiosity's avatar

I suppose you are suggesting that I could comment out that line and then stick everything I want csrf verified in a route group?

thoasty's avatar

Look inside the VerifyCsrfToken.php :

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

Should be self-explaining. You can even use a wildcard (*). But be sure to enter the URIs ('/path'), not the route names.

Regards.

1 like
curiosity's avatar

Yes I understand you can use except. I'm looking to do this via applying a middleware class.

Route::post('my-route', ['as'=>'myRoute', 'uses'=>'MyController@index', 'middleware'=>'no_csrf']);
atishrajput's avatar

app/Http/Middleware/VerifyCsrfToken.php :

class VerifyCsrfToken extends BaseVerifier {

protected $except = [
    'my-route/*'
];

}

1 like
thoasty's avatar

Hack inside your middleware:

$request->offsetSet('_token', $request->session()->token());

Please or to participate in this conversation.