3

I am getting issues with CSRF exceptions being thrown to the user. They happen for perfectly innocent reasons like if someone takes too long to fill out a form when they finally submit it the session has expired and the tokens don't match. Now obviously this is an error but it doesn't need to kill everything and throw an exception.

Is there a way to just get it to set a flash message instead and redirect back to the original page. I don't want to disable CSRF protection I just want the errors to be handled a bit more gracefully.

geoffs3310
  • 5,599
  • 11
  • 51
  • 104

2 Answers2

4

This is a bit of a pain, I usually add a method to the VerifyCsrfToken class to catch the TokenMismatchException (in the Middleware folder):

public function handle($request, Closure $next)
{
    try
    {
        return parent::handle($request, $next);
    } 
    catch(TokenMismatchException $e)
    {
        return redirect()->back()->withInput()->withErrors(['tokenMismatch' => 'Have you been away? Please try submitting the form again!']);
    }
}

Although, you might want to tweak that depending on how you are handling errors in your app.

craig_h
  • 31,871
  • 6
  • 59
  • 68
  • I've done that however I now get the following error: Argument 2 passed to App\Http\Middleware\VerifyCsrfToken::handle() must be an instance of App\Http\Middleware\Closure, instance of Closure given – geoffs3310 Oct 14 '15 at 14:45
  • 5
    I think you just need to put `use Closure;` at the top of you class, just below `namespace App\Http\Middleware;` or you can place a backslash at the start of the declaration: `public function handle($request, \Closure $next)`. – craig_h Oct 14 '15 at 14:49
1

This can be handled in app/Handler.php

Change the render function from

public function render($request, Exception $e)
{
    return parent::render($request, $e);
}

To this:

public function render($request, Exception $e)
{
    if ($e instanceof \Illuminate\Session\TokenMismatchException){

        return redirect($request->fullUrl())->with('error',"Sorry your session has expired please resubmit your request.");
    }
    return parent::render($request, $e);
}
geoffs3310
  • 5,599
  • 11
  • 51
  • 104