Laravel 5.1 prevent CSRF mismatch from throwing ex

2019-07-04 01:09发布

This question already has an answer here:

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.

2条回答
成全新的幸福
2楼-- · 2019-07-04 01:27

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);
}
查看更多
Evening l夕情丶
3楼-- · 2019-07-04 01:42

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.

查看更多
登录 后发表回答