Ad

How To Disable Csrf Protection For A Route With Dynamic Parameter?

- 1 answer

I have a route which has a dynamic parameter at the end of the URL. In this route, I fetch data which is sent from an external API with the post method. As 419 page expired error occurs when the external API sends post request, I need to disable csrf protection for this route.

Related route:

Route::group(['middleware' => ['auth:student']], function (){
    Route::post('Result', '[email protected]')->name('exam.Result');
}

My URL example:

http://localhost.dev/student/Result?Id=N7utfGkwOLebxMWGA5iUC4S23jgRzW

I tried to add this code in VerifyCsrfToken file at App\Http\Middleware:

protected $except = [
'student/Result/*',
];

It doesn't work. But when I try student/*, it works perfectly. However, disabling the csrf protection for all student path is not what I want.

I tried also this way by getting reference on this thread:

Route::post('Result', [
      'uses' => '[email protected]',
      'nocsrf' => 'true'
    ])->name('exam.Result');

That didn't work either.

How can I disable csrf protection in this scenario?

Ad

Answer

You made a typo at App\Http\Middleware, instead of:

protected $except = [
'student/Result/*',
];

You need to use:

protected $except = [
'student/Result',
];

Also, based on documentation you can specify the full url that need to be excepted:

protected $except = [
'http://localhost.dev/student/Result',
];

Be aware, that you don't need to add parameters part (everything after ? sign, e.g. ?Id=N7utfGkwOLebxMWGA5iUC4S23jgRzW) of route here.

Ad
source: stackoverflow.com
Ad