0

Sometimes, when laravel_session cookie expired and I'm still on the page, I would log in and get the TokenMismatchException error. This is understandable.

I would like to handle this case, e.g. by showing some kind of error to the user and redirecting. If possible, I would like to catch it only for the login request.

The main problem is that the CSRF token is checked by a global middleware, so the error gets thrown before I can handle it with try-catch block in a controller action.

Another problem is that the VerifyCsrfToken.php in the app/Http/Middeware directory, which looks like this:

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

I can't see how I could use the code above to catch the TokenMismatchException. Seems like I can only exclude specific URIs.

Is there any way I can do that?

lesssugar
  • 15,486
  • 18
  • 65
  • 115
  • Do you really have users idle for N hours who then want to use the application? Extend the session time then. – Rápli András Dec 15 '16 at 11:34
  • If you caught TokenMismatchException, you put yourself at security risk. It makes no sense. – Rápli András Dec 15 '16 at 11:34
  • I would preferably catch the exception only for the login request, not globally. Also, extending session time is not a solution for me. The session is set to 2 hours, and there are users who still have this problem. – lesssugar Dec 15 '16 at 11:37
  • Then make a middleware that redirects users with the invalidated session to the login page before token mismatch could happen. Before login, there's no session created, so there could be no error with this. – Rápli András Dec 15 '16 at 11:48

1 Answers1

2

Go to app\Exceptions\Handler.php and test it like this:

//Add this to render() method:

if ($exception instanceof TokenMismatchException) {
   return $this->handleTokenMismatchException($exception);
}

// then...

protected function handleTokenMismatchException(TokenMismatchException $exception) {

    // What you gonna do about it e.g. return redirect('/somewhere');

}
Hudson Pereira
  • 1,066
  • 8
  • 13