Reputation: 2154
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.
Upvotes: 2
Views: 98
Reputation: 1366
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")
}
});
Upvotes: 1
Reputation: 396
I have a problem like yours; maybe this answer will help ..It look like your csrf token is updated : https://stackoverflow.com/a/43893114/5586645
Upvotes: 0
Reputation: 2123
Try doing it like this instead: https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
Add this to your <head></head>
inside your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
And in your JS get the token like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').val()
}
});
-- edit --
You can use an input field instead if you do not want to use a meta
tag and put this in your <body></body>
<input type="hidden" name="csrf-token" value="{{ csrf_token() }}">
'X-CSRF-TOKEN': $('input[name="csrf-token"]').val()
Upvotes: 1