Monday, March 20, 2017

How to prevent the TokenMismatchException reliably during Ajax calls in Laravel?

I know there have been many questions asked before about handling the CSRF token on Ajax calls in Laravel. The Laravel docs specify a way to pass the csrf_token value on any Ajax request like this:

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

and this is exactly what I'm doing in my app.

However, there are still plenty of cases when the TokenMismatchException gets thrown and logged on the server. I think one reason for this is the following:

  1. User loads a page and leaves the page open
  2. Laravel session expires
  3. The user gets back to the PC and triggers an Ajax call (e.g. by clicking on a button)
  4. The Ajax call gathers the csrf-token value from the meta tag

Now, the csrf-token value passed wth the call is, of course, wrong now, as Laravel session doesn't exist and needs to be regenerated.

Laravel docs also suggests using the XSRF-TOKEN cookie. However, the cookie has - obviously - the same expiration date as the laravel_session cookie, which won't help me either.

Notice that the user doesn't necessarily have to be authenticated to generate Ajax calls, they can be fired by guest users, and all are checked against cross-site request forgery.

Is there a way to get around this and prevent the TokenMismatchException in situations like I described above?



via lesssugar

Advertisement