1

I have a laravel application which outputs the token in a field on every page. Then jquery loads the token to every ajax request, as answered here: Laravel 5 CSRF global token hidden field for all forms in a page

But every once in a while, I get TokenMismatch Exceptions on ajax calls.. sometimes it happens when the website is idle for too long, and sometimes it's just apparently random.

Any ideas on how to debug this? What may be causing this, or possible solutions?

Community
  • 1
  • 1
sigmaxf
  • 7,998
  • 15
  • 65
  • 125

4 Answers4

1

i think you should not turn-off the VerifyCsrfToken middleware on your Kernel.php file because this action can invite attacks. actually you need to protect every request to your site with token(excluding the case of external post to our site eg:mandrill status post).

set meta-tag like follows

<meta name="csrf-token" content="{{ csrf_token() }}">

then request like follows

$.ajax({
    data: {data1:'data1',data2:'data2'},
    url: '/your/url/goes/here',
    type: 'POST',
    beforeSend: function (request) {
        return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
    },
    success: function(response){
        console.log(response);
    }
})
Rameez Rami
  • 5,322
  • 2
  • 29
  • 36
1

Add below html code in you main view file.

<meta name="csrf-token" content="{{ csrf_token() }}">

Always use below script on your JS file or view file.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47
0

If you need to do AJAX request, turn-off the VerifyCsrfToken middleware on your Kernel.php file.

You can also edit your VerifyCsrfToken.php middleware file to exclude certain URLs like this way:

/** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'ajax/*', 'api/*', ];

  • I don't think it's wise to disable a security feature. It's better to learn how to use it properly. – Ferares Mar 01 '23 at 17:34
0

The reason this happens is most likely one of the following:

  1. You've been idle for too long – by default, the CSRF tokens are valid for 15 minutes of I'm not mistaken.

  2. You're forgetting to pass the token to your backend. This can be done by simply adding the X-CSRF-TOKEN header to your request.

Phroggyy
  • 423
  • 3
  • 10