Laravel 捕获 TokenMismatchException
Laravel catch TokenMismatchException
可以使用 try catch 块捕获 TokenMismatchException 吗?我不想显示显示 "TokenMismatchException in VerifyCsrfToken.php line 46..." 的调试页面,而是希望它显示实际页面并仅显示一条错误消息。
CSRF 没有问题,我只是希望它仍然显示页面而不是调试页面。
要复制(使用 firefox):
步骤:
- 打开页面(http://example.com/login)
- 清除 Cookie(域、路径、会话)。我在这里使用 Web 开发人员工具栏插件。
- 提交表格。
实际结果:"Whoops, looks like something went wrong" 页面显示。
预期结果:仍然显示登录页面,然后传递 "Token mismatch" 或其他内容的错误。
请注意,当我清除 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>
这里没什么特别的。只是一个普通的表格。就像我所说的那样,表格工作得很好。就在我说上述步骤时,由于TOKEN过期而出错。我的问题是,表格应该那样做吗?我的意思是,每当我清除 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);
}
}
与其尝试捕获异常,不如将用户重定向回同一页面并让 him/her 再次重复该操作。
在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.');
}
}
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();
}
}
更好的Laravel 5解决方案
在App\Exceptions\Handler.php
Return 用户使用新的有效 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);
}
我也很喜欢这个创意:
Laravel 8 处理异常的方式似乎略有不同,上述解决方案中的 none 在我全新安装的 Laravel 中有效。所以我发布了我最终开始工作的内容,希望它能对其他人有所帮助。参见 Laravel Docs here。
这是我的 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.
}
});
}
}
不错。 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.');
}
});
可以使用 try catch 块捕获 TokenMismatchException 吗?我不想显示显示 "TokenMismatchException in VerifyCsrfToken.php line 46..." 的调试页面,而是希望它显示实际页面并仅显示一条错误消息。
CSRF 没有问题,我只是希望它仍然显示页面而不是调试页面。
要复制(使用 firefox): 步骤:
- 打开页面(http://example.com/login)
- 清除 Cookie(域、路径、会话)。我在这里使用 Web 开发人员工具栏插件。
- 提交表格。
实际结果:"Whoops, looks like something went wrong" 页面显示。 预期结果:仍然显示登录页面,然后传递 "Token mismatch" 或其他内容的错误。
请注意,当我清除 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>
这里没什么特别的。只是一个普通的表格。就像我所说的那样,表格工作得很好。就在我说上述步骤时,由于TOKEN过期而出错。我的问题是,表格应该那样做吗?我的意思是,每当我清除 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);
}
}
与其尝试捕获异常,不如将用户重定向回同一页面并让 him/her 再次重复该操作。
在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.');
}
}
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();
}
}
更好的Laravel 5解决方案
在App\Exceptions\Handler.php
Return 用户使用新的有效 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);
}
我也很喜欢这个创意:
Laravel 8 处理异常的方式似乎略有不同,上述解决方案中的 none 在我全新安装的 Laravel 中有效。所以我发布了我最终开始工作的内容,希望它能对其他人有所帮助。参见 Laravel Docs here。
这是我的 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.
}
});
}
}
不错。 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.');
}
});