Search code examples
phplaravelcsrfmiddlewarecsrf-token

Turn on CSRF protection for a group of GET routes in Laravel


I have the following group of GET routes on Laravel:

Route::get('/location/get', 'Ajax@getProducts');
Route::get('/products/get', 'Ajax@getProducts');
Route::get('/schedule/get', 'Ajax@getProducts');

I want to protect those routes with the automatically generated CSRF token from Laravel.

I have read some workarounds about overriding method: VerifyCsrfToken@isReading(...), but I'm not too much convinced about that.

Then I'm looking for a more elegant solution.

Thanks!


Solution

  • CSRF is not protecting your data. More info: https://security.stackexchange.com/a/115808

    If you has no reason for using GET method with CSRF, just use POST with default csrf middleware group:

    Route::group(['before' => 'csrf'], function() {
        // your ::post routes
    });
    

    Anyway, you can try to create VerifyCsrfTokenAll middleware, and use csrf_get key from this answer: https://stackoverflow.com/a/41656322/2453148 and then wrap your routes in this group:

    Route::group(['before' => 'csrf_get'], function() {
        // your routes
    });