可以使用try catch块捕获TokenMismatchException吗?我希望它不显示显示“ VerifyCsrfToken.php第46行中的TokenMismatchException …”的调试页面,而是希望它显示实际页面并仅显示错误消息。
我对CSRF没问题,我只希望它仍然显示页面而不是调试页面。
复制(使用Firefox):步骤:
实际结果:显示“糟糕,看起来好像出了点问题”页面。预期结果:仍显示登录页面,然后传递“令牌不匹配”之类的错误。
请注意,当我清除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" /> <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和会话时,也需要重新加载页面吗?CSRF在这里是这样工作的吗?
您可以在 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); } }