2

Laravel 5.3

I wish handle TokenMismatchException in VerifyCsrfToken.php. Normally this exception occurs when I haven't refresh current page, and the previous token persist, so I reload the page, new token is set and I can do login process. Ok, but, I wish handle the exception and refresh automatically the page.

Is this possible?

FilippoLcr
  • 119
  • 2
  • 10

1 Answers1

3

If you still wish to handle Handle TokenMismatchException in VerifyCsrfToken.php Here is the way forward in laravel 5.3. find the VerifyCsrfToken.php In a middleware directory

app\Http\Middleware\VerifyCsrfToken.php

make sure you add,

use Closure;

to avoid Declaration exception error. Then add the handle method to compare sessionToken and form input Token.

public function handle($request, Closure $next)
{
  if($request->input('_token'))
  {
    if ( \Session::getToken() != $request->input('_token'))
    {

      notify()->flash('Your session has expired. Please try logging in again.', 'warning');

      return redirect()->guest('/login');
    }
  }
  return parent::handle($request, $next);
}

A vivid insight: Totally optional

  • Checking If Session token matches request token(The token in the input hidden)

dd(\Session::getToken() == $request->input('_token'));

  • Log an error that the session has expired its totally optional

\Log::error("Expired token found. Redirecting to /");

  • flash the error message with redirect response to the login page

return redirect()->guest('/') ->with('global', 'Expired token found. Redirecting to /');

  • note:

    If this if statement is not true , the return value(return parent::handle($request, $next);) will be excuted that means if there is the a problem with a token, An Error Exception will be thrown (TokenMismatch exception). This may be because by forgetting adding the {{ csrf_field() }} in the form so as the result the $request->input('_token') can not be found or its empty.

  • Notice:

    Am using codecourse/notify (https://github.com/codecourse/notify) to flash message thats why i used,

notify()->flash('Your session has expired. Please try logging in again.', 'warning');

its totally optional if you want to flash message without the package. You can use laravel implimentation. So it will be something like

return redirect()->guest('/') ->with('global', 'Expired token found. Redirecting to /');

mtuchi
  • 31
  • 2