Laravel 捕获 TokenMismatchException

问题描述 投票:0回答:7

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

我对 CSRF 没有任何问题,我只是希望它仍然显示页面而不是调试页面。

复制(使用 Firefox): 步骤:

  1. 打开页面(http://example.com/login
  2. 清除 Cookie(域、路径、会话)。我在这里使用网络开发人员工具栏插件。
  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>

这里没什么特别的。只是一个普通的形式。就像我所说的,该表格工作得很好。只是当我说出上述步骤时,由于TOKEN已过期而出错。我的问题是,表单应该这样做吗?我的意思是,当我清除 cookie 和会话时,我也需要重新加载页面吗? CSRF 就是这样工作的吗?

php laravel exception csrf laravel-5
7个回答
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);
    }
}

18
投票

更好的 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


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

4
投票

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

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

}

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

0
投票

这是我可以在 Laravel 9 中使用的唯一解决方案:

if ($status === 419) {
    return back()
    ->withErrors(['error' => 'Session expired for security reasons. Try again.'])
    ->withInput($request->except('_token'));
}

注意

error
键,它应该存在于您要重定向到的页面上的错误包中 - 这是错误将呈现到的位置。

© www.soinside.com 2019 - 2024. All rights reserved.