php Laravel 捕获 TokenMismatchException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29115184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:14:45  来源:igfitidea点击:

Laravel catch TokenMismatchException

phplaravelexception-handlingcsrflaravel-5

提问by basagabi

Can the TokenMismatchException be catched using try catch block? Instead of displaying the debug page that shows the "TokenMismatchException in VerifyCsrfToken.php line 46...", I want it to display the actual page and just display an error message.

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

I have no problems with the CSRF, I just want it to still display the page instead of the debug page.

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

To replicate (using firefox): Steps:

复制(使用 Firefox): 步骤:

  1. Open page (http://example.com/login)
  2. Clear Cookies (Domain, Path, Session). I am using web developer toolbar plugin here.
  3. Submit form.
  1. 打开页面 ( http://example.com/login)
  2. 清除 Cookie(域、路径、会话)。我在这里使用 Web 开发人员工具栏插件。
  3. 提交表格。

Actual Results: "Whoops, looks like something went wrong" page displays. Expected Results: Still display the login page then pass an error of "Token mismatch" or something.

实际结果:“糟糕,好像出了点问题”页面显示。预期结果:仍然显示登录页面,然后传递“令牌不匹配”或其他错误。

Notice that when I cleared the cookies, I didn't refresh the page in order for the token to generate a new key and force it to error out.

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

UPDATE (ADDED FORM):

更新(添加表格):

        <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>

Nothing really fancy here. Just an ordinary form. Like what I've said, the form is WORKING perfectly fine. It is just when I stated the above steps, it errors out due to the TOKEN being expired. My question is that, should the form behave that way? I mean, when ever I clear cookies and session I need to reload the page too? Is that how CSRF works here?

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

回答by Emeka Mbah

You can handle TokenMismatchException Exception in App\Exceptions\Handler.php

您可以在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);
    }
}

回答by Neo

A Better Laravel 5 Solution

一个更好的Laravel 5 解决方案

in App\Exceptions\Handler.php
Return the user to the form with a new valid CSRF token, so they can just resubmit the form without filling the form again.

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

I also really like this idea:

我也很喜欢这个想法:

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

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

回答by Lee

Instead of trying to catch the exception just redirect the user back to the same page and make him/her repeat the action again.

与其尝试捕获异常,不如将用户重定向回同一页面并让他/她再次重复该操作。

Use this code in the App\Http\Middleware\VerifyCsrfToken.php

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

回答by MDR

Laravel 5.2: Modify App\Exceptions\Handler.phplike this:

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

In AJAX requests you can respond to the client using abort() function and then handle the response in client side using AJAX jqXHR.status very easily, for example by showing a message and refreshing the page. Don't forget to catch the HTML status code in jQuery ajaxComplete event:

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