Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sazr's avatar
Level 1

My AJAX post contains the correct token header but I still get a TokenMismatchException

I have an Angular.js and Laravel web application. All my ajax posts and get requests to the laravel app/server result in a TokenMismatchException even though my requests do contain the headers X-CSRF-TOKEN and _token with the correct values.

What the heck could be going wrong here? I'm quite confused what the issue is. I'll explain relevant information below and hopefully you can provide some insight.

routes.php:

Route::group(array('middleware' => 'auth'), function () {
    ....

    Route::group(array('middleware' => 'admin', 'prefix' => 'admin'), function () {

        Route::get('foo', array(
            'as' => 'foo-bar',
            'uses' => 'AdminController@myFoo'  // myFoo does nothing but return some json dummy text
        ));
    }
}

AdminMiddleware.php:

class AdminMiddleware
{
    protected $auth;

    public function __construct(Guard $auth) {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        if (!$this->auth->user()->is_Admin) {
            return Redirect::route('home');
        }
        return $next($request);
    }
}

VerifyCsrfToken.php:

class VerifyCsrfToken extends BaseVerifier {

    public function handle($request, Closure $next)
    {
        // Below I confirm that the request headers do 
        // contain X-CSRF-TOKEN and _token and have the correct values
        Log::info(print_r($request, true));

        return parent::handle($request, $next);
    }

}

MyController.js:

adminSector.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    // I have confirmed that the meta tag below is in the HTML head element and contains the correct token
    $http.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
    $http.defaults.headers.common['_token'] = $('meta[name="csrf-token"]').attr('content');

    // Function called when I click a button
    $scope.foo = function () {
        $http./*post*/get('/admin/foo').success(function (data) {
            console.log('data', data); 
        });
    };

    ...

So the above post call fails with the error: TokenMismatchException in VerifyCsrfToken.php line 67:. But if I login as an admin and just go directly to http://mywebsite.com/admin/foo it succeeds and shows the JSON response. What the heck is going wrong?

0 likes
2 replies
jobcerto's avatar
 Route::get('foo',
$http.post('/admin/foo').

the correct is $http.get right?

Please or to participate in this conversation.