Laravel 5.1 prevent CSRF mismatch from throwing exception [duplicate]

。_饼干妹妹 提交于 2019-12-14 03:48:57

问题


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.


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/33121192/laravel-5-1-prevent-csrf-mismatch-from-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!