jeudi 28 avril 2016

CSRF Token not working in Laravel 5.1 Exceptions Handler with an Ajax request

I have a Laravel 5.1 application with Ajax content loaded at start up.

I have placed the CSRF meta tag to page head:

<meta name="csrf-token" content="" />

And I use it in jquery ajax requests:

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

Everything works perfectly under normal circumstances. But when I open a 404 error page without a previous session, my ajax requests get an error: TokenMismatchException in VerifyCsrfToken.php

I have an 404 error handler in file: app\Exceptions\Handler.php

public function render($request, Exception $e)
{
  if ($e instanceof NotFoundHttpException)
  {
    $foo = \App\Foo::foo();
    return \Response::make(view("errors.404", compact("foo")), 404);
  }

  return parent::render($request, $e);
}

I can repeat this error by opening a private browser window and opening my site with an url to a non existing page. It persists on page reloads. But if I go to an existing page and try the 404 url again, it works fine.

Any ideas how fix this problem?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire