Ad

Laravel TokenMismatch Exception When Sending Token In Header

I am sending CSRF token in header while making an ajax request.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': getCookie("XSRF-TOKEN")
    }
});

In the above code I am getting the token from "XSRF-TOKEN" cookie and setting in "X-CSRF_TOKEN" header globaly for all ajax requests.

I've checked in chrome developers tool that this header is being sent.

But Laravel still throws TokenMismatch exception.

Note I can not get token from html like meta tag or input fields becuase html content is being cached therefore I would like to set use "XSRF-TOKEN" cookie that laravel sets in every response.

Ad

Answer

The token generated by Laravel's csrf_token() and the one that is set in the cookie are not the same.

Now the problem is the "X-CSRF-TOKEN" header is used to send token generated by csrf_token() function.

Therefore if you want to send csrf token obtained from cookie you should use "X-XSRF-TOKEN" header.

Hence the above code should be like

$.ajaxSetup({
    headers: {
        'X-XSRF-TOKEN': getCookie("XSRF-TOKEN")
    }
});
Ad
source: stackoverflow.com
Ad