Laravel捕获TokenMismatchException

55

TokenMismatchException可以使用try catch块捕获吗?我想要它显示实际页面并只显示错误消息,而不是显示显示“ VerifyCsrfToken.php第46行的TokenMismatchException ...” 的调试页面。

CSRF没有问题,我只是想让它继续显示页面而不是调试页面。

复制(使用Firefox):

  1. 打开页面(http://example.com/login
  2. 清除Cookie(域名、路径、会话)。我在这里使用Web Developer工具栏插件。
  3. 提交表单。

实际结果:显示“哎呀,似乎出了些问题”的页面。 期望结果:仍然显示登录页面,然后传递“令牌不匹配”或类似的错误。

请注意,当我清除Cookie时,我没有刷新页面以生成新密钥并强制出错。

更新(添加表单):

        <form class="form-horizontal" action="<?php echo route($formActionStoreUrl); ?>" method="post">
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>" />
        <div class="form-group">
            <label for="txtCode" class="col-sm-1 control-label">Code</label>
            <div class="col-sm-11">
                <input type="text" name="txtCode" id="txtCode" class="form-control" placeholder="Code" />
            </div>
        </div>
        <div class="form-group">
            <label for="txtDesc" class="col-sm-1 control-label">Description</label>
            <div class="col-sm-11">
                <input type="text" name="txtDesc" id="txtDesc" class="form-control" placeholder="Description" />
            </div>
        </div>
        <div class="form-group">
            <label for="cbxInactive" class="col-sm-1 control-label">Inactive</label>
            <div class="col-sm-11">
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name="cbxInactive" id="cbxInactive" value="inactive" />&nbsp;
                        <span class="check"></span>
                    </label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-12">
                <button type="submit" class="btn btn-primary pull-right"><i class="fa fa-save fa-lg"></i> Save</button>
            </div>
        </div>
    </form>

这里没有什么特别的东西,只是一个普通的表单。正如我所说,表单完全正常地工作着。只是当我执行上述步骤时,由于令牌过期而出现错误。我的问题是,这个表单是否应该这样运行?我的意思是,每当我清除 cookie 和 session 时,我都需要重新加载页面吗?这就是 CSRF 在这里起作用的方式吗?


什么形式?这个页面是一个空白的示例。 - Félix Adriyel Gagnon-Grenier
请发布您表单的代码,我们需要看看哪里出了问题。 - sybear
还有您的路由。 - sybear
有没有任何理由不添加一个2小时的meta refresh或者过期时间? - Justin
6个回答

101
您可以在 App\Exceptions\Handler.php 中处理 TokenMismatchException 异常。
<?php namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;


class Handler extends ExceptionHandler {


    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];
    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        return parent::report($e);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof TokenMismatchException){
            // Redirect to a form. Here is an example of how I handle mine
            return redirect($request->fullUrl())->with('csrf_error',"Oops! Seems you couldn't submit form for a long time. Please try again.");
        }

        return parent::render($request, $e);
    }
}

13
未来读者注意:不要忘记在顶部添加use声明,否则$e instanceof TokenMismatchException将为false。 - DisgruntledGoat
你成功测试过这个程序处理异常的功能吗?我无法让它正常工作。 - simonhamp
3
您可以在 Blade 模板中使用 @if (session('csrf_error')) {{ session('csrf_error') }} @endif 显示此错误信息。 - Eranda
3
这个例子适用于Laravel 5.3,我建议使用->withErrors('Oops ....'),并且可以尝试使用redirect()->back()->withErrors。 - WoodyDRN
这会在 Ajax 请求中返回适当的响应吗? - Sumit Kumar

17

更好的 Laravel 5 解决方案

App\Exceptions\Handler.php
返回带有新有效 CSRF 令牌的表单给用户,这样他们可以重新提交表单而无需再次填写表单。

public function render($request, Exception $e)
    {
         if($e instanceof \Illuminate\Session\TokenMismatchException){
              return redirect()
                  ->back()
                  ->withInput($request->except('_token'))
                  ->withMessage('Your explanation message depending on how much you want to dumb it down, lol!');
        }
        return parent::render($request, $e);
    }

我也非常喜欢这个想法:

https://github.com/GeneaLabs/laravel-caffeine


我使用自己的咖啡因概念变体,但似乎失败了。我不确定原因,但我怀疑可能是标签在后台,因此JavaScript被暂停,它从未刷新令牌或其他奇怪的问题。或者他们通过关闭笔记本电脑盖子将计算机置于睡眠状态。因此,良好处理错误令牌应该比尝试保持令牌刷新更好。至少在我的情况下是这样。 - Dustin Graham
如何在Laravel 5.4.24中访问由withInput()发送的返回输入数据? - Yogesh Mistry

12

不要试图捕获异常,而是将用户重定向回相同的页面,并让他/她再次重复操作。

在App\Http\Middleware\VerifyCsrfToken.php中使用此代码。

<?php
namespace App\Http\Middleware;
use Closure;
use Redirect;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];

    public function handle( $request, Closure $next )
    {
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
            $this->tokensMatch($request)
        ) {
            return $this->addCookieToResponse($request, $next($request));
        }

        // redirect the user back to the last page and show error
        return Redirect::back()->withError('Sorry, we could not verify your request. Please try again.');
    }
}

6
这个答案已经过时了,针对5.4版本,$this->shouldPassThrough($request)现在改为$this->inExceptArray($request) - Brendan

4

Laravel 8似乎对异常处理方式略有不同,上述解决方案在我新安装的Laravel中均无效。因此,我会发布我最终得到的可行解决方案,并希望它能对其他人有所帮助。请参见Laravel文档

这是我的App\Exceptions\Handler.php文件:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, $request) {
            if ($e->getStatusCode() == 419) {
                // Do whatever you need to do here.
            }
        });
    }

}

1
非常好用。谢谢。我一直在尝试直接处理TokenMismatchException,但是没有成功。 - noviolence

3

Laravel 5.2: 按照以下方式修改App\Exceptions\Handler.php

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Illuminate\Session\TokenMismatchException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($e instanceof TokenMismatchException) {
            abort(400); /* bad request */
        }
        return parent::render($request, $e);
    }
}

在 AJAX 请求中,可以使用 abort() 函数响应客户端,然后使用 AJAX jqXHR.status 在客户端轻松处理响应,例如显示消息并刷新页面。 不要忘记在 jQuery ajaxComplete 事件中捕获 HTML 状态码:

$(document).ajaxComplete(function(event, xhr, settings) {
  switch (xhr.status) {
    case 400:
      status_write('Bad Response!!!', 'error');
      location.reload();
  }
}

1
不错的 AJAX 考虑,为什么不顺便传递一条消息呢?abort('400', '您的表单已过期!'); - Harry Bosh

2
很好。 Laravel 8 以不同的方式实现了这一点。 下面的代码块在 Laravel 8 中无法正常工作。
  if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
    return redirect()->route('login');
  }

但是这一个确实可以:
  $this->renderable(function (\Symfony\Component\HttpKernel\Exception\HttpException $e, $request) {
    if ($e->getStatusCode() == 419) {
      return redirect('/login')->with('error','Your session expired due to inactivity. Please login again.');
    }
  });
 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接