Thursday, March 2, 2017

laravel shows old CSRF tokens resulting in a tokenmismatchException

I'm using Laravel for a project where I need the CSRF token for API calls. My CSRF meta tag sometimes contains tokens that are expired. By refreshing it's good to go for like 10 new calls. So after like 10 refreshes I get the TokenMismatchException from my AJAX calls. Making this API call an CSRF exception is not an option because the API call is heavy-loaded and contains valuable information.

I didn't customize any middelware classes.

My AJAX call in javascript looks like this:

$.ajax({
        url: '/getAllProducts',
        type: 'POST',
        data: {
            type: "gpu",
            hash: md5hash,
            _token: $('meta[name="csrf-token"]').attr('content')

        },
        dataType: 'json',
        success: function (response) {
            md5hash = '';
            products = response;
            $('.more-information').fadeIn();
            $.getScript("/js/filter-products.js", function(){
                filterProducts();
            });

            $.getScript("/js/createPopup.js", function(){
                $('.more-information').on('click', createPopup);
                $('.open-details').on('click', createPopup);
            });
        }
    });

My route looks like this

route::post('/getAllProducts', 'PartsController@getAllProducts');

The meta csrf token is generated like the standard Laravel app.blade.php

<meta name="csrf-token" content="">

I'm aware there are other questions about this issue but I didn't find a solution. I tried several of them.

Here is the list of solutions I tried:

  • add jquery Ajaxsetup
  • update laravel
  • clear cache

Really hope someone can help me



via Wesley Kroon

Advertisement