Reputation: 5069
In an app which mixes Laravel and Angular, I have this persistent CSRF token mismatch
error coming up when calling a route from an Angular service. This is more or less how it's set up:
ROUTES
Route::group(['middleware' => ['web'] ], function () {
// non-auth routes (e.g. signup, login) ...
Route::group(['middleware' => 'auth'], function() {
Route::get('w/{ignore?}', function () { return view('writer.index');})
->where('ignore', '.*');
Route::match(['get', 'post'], 'doc/open', 'Controller@openItem');
});
});
The writer.index
view shows up fine without token error (the user has been authenticated).
The VIEW includes:
<meta name="csrf-token" content="{{ csrf_token() }}" />
and
<script>
$(function(){
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
});
});
</script>
From Angular, a service is producing a request to the doc/open
route over $http.post
which returns the token mismatch error
.
I checked the headers and the $http.post
did in fact send over a value for X-XSRF-TOKEN
. However, this header value does not match the XSRF-TOKEN
value in the cookie. If that's the mismatch, why is it occurring?
Upvotes: 0
Views: 2145
Reputation: 75
In laravel 5.3, this is made simple with Passport package. I was having the same trouble with Angular resource requests. I fixed it by installing Passport via composer and adding the following lines to
app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
\stix\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\stix\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Now laravel will automatically include X-CRSF-TOKEN for every request made within the web middleware group. Hope this helps.
Upvotes: 1