I am building a REST API using Laravel 5.1 and I am getting this error:
TokenMismatchException in VerifyCsrfToken.php line 53:
I was getting the same error, but with all the warnings about overriding CSRF validation, didn't want to change those settings.
I eventually found that my Session Driver in /config/session.php was defaulting to memcached, and since I was on a development server I needed to override the SESSION_DRIVER env variable with 'file' to use the session in /storage/framework/sessions.
/.env
SESSION_DRIVER = file
You do not need to fully override the CFSR token from your app. In your App/Http/Midlleware folder go to VerifyCsrfToken.php and include your API route to the exception as follows:
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'api/*',
];
The * shows for all routes inside your API.
If you are building an API its best to place the CRSF middle ware on per route basis rather than placing it as a global middleware. To make it as a route middleware go to the "/app/Http/Kernel.php" file.
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
//comment out to avoid CSRF Token mismatch error
// 'App\Http\Middleware\VerifyCsrfToken',
];
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'cors' => 'App\Http\Middleware\CorsMiddleware',
'api' => 'App\Http\Middleware\ApiMiddleware',
'csrf' => 'App\Http\Middleware\VerifyCsrfToken'// add it as a middleware route
Now you can place it on the routes where you need it for example
Route::get('someRoute', array('uses' => 'HomeController@getSomeRoute', 'middleware' => 'csrf'));
For your case where you don't need CSRF token matching it should work fine now.