W
W
WebDev2016-03-29 16:06:31
Laravel
WebDev, 2016-03-29 16:06:31

Laravel Token mismatch exception?

There is a page, the page has a lot of functionality through ajax. All post requests are checked against csrf. After a certain time, if you do not reload the page, Ajax requests stop working because the token has changed.
What to do in this case? Can I remove ajax requests from the check?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
Zend_Arbitr, 2016-04-09
@kirill-93

It's just that the lifetime of the token is set to 2 hours by default. You can see this in Illuminate\Foundation\Http\Middleware\VerifyCsrfToken in the addCookieToResponse method.

protected function addCookieToResponse($request, $response)
  {
    $response->headers->setCookie(
      new Cookie('XSRF-TOKEN', $request->session()->token(), time() + 60 * 120, '/', null, false, false)
    );

    return $response;
  }

You need to overload the method with your data in App\Http\Middleware\VerifyCsrfToken. Here is a working example, we take the time from the config (it is indicated there in minutes, as is customary in the Laravel config), converting it to seconds:
protected function addCookieToResponse($request, $response)
    {
        $response->headers->setCookie(
            new Cookie('XSRF-TOKEN', $request->session()->token(), time() + Config::get("session.lifetime")*60, '/', null, false, false)
        );
        return $response;
    }

I
i_albakov, 2016-07-31
@i_albakov

You can also use this https://github.com/GeneaLabs/laravel-caffeine - sends requests every time the session time expires.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question