Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel CSRF protection with REST API

I have this code at the top of my routes file

Route::when('*', 'csrf', array('post', 'put', 'delete'));

When I testing my RESTful API layer I get token mismatch error. How to solve this?

I use CSRF protection for regular form submissions a user might do. But how would that work for an API? I have my API calls grouped after my regular routes as below

Route::group(array('prefix' => 'api'), function () {
Route::resource('shows', 'ShowsApiController');
Route::resource('episode', 'EpisodesApiController');
Route::resource('genre', 'GenresApiController');
});
like image 448
Vijayanand Premnath Avatar asked May 10 '16 08:05

Vijayanand Premnath


2 Answers

You should consider using different middleware groups for Your web and api layers. Laravel by default, depending on version You are using, uses web middleware group.

If You are not having line like this Route::group(['middleware' => 'web'], function () { in Your routes.php file, then Your laravel version is that one which uses it by default. Check Your RouteServiceProvider.php file for this line: https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L56.

If presented, remove 'middleware' => 'web' part and group routes Yourself in routes.php. Then use web middleware for part where You need sessions, csrf and other stuff, and use api middleware where You don't need these things (api middleware group does not include sessions, encrypted cookies and csrf verifications).

like image 52
Giedrius Kiršys Avatar answered Oct 19 '22 20:10

Giedrius Kiršys


In your App\Http\Middleware\VerifyCsrfToken

you will have such a class, add your routes to the $except

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
  protected $except = [
    'shows/*',
    'episode/*',
    'genre/*',
  ];
}
like image 25
Achraf Khouadja Avatar answered Oct 19 '22 22:10

Achraf Khouadja