简体   繁体   中英

CSRF token mismatch in Laravel / Angular app

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM