2

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.

Amarjit Singh
  • 2,068
  • 19
  • 52

3 Answers3

1

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()
H H
  • 2,065
  • 1
  • 24
  • 30
1

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")
    }
});
Harat
  • 1,340
  • 1
  • 17
  • 20
0

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

Roland Allla
  • 388
  • 4
  • 13