可以使用try catch块捕获TokenMismatchException吗?而不是在VerifyCsrfToken.php第46行..."中显示显示" TokenMismatchException的调试页面,我希望它显示实际页面并只显示错误消息。
我对CSRF没有任何问题,我只是希望它仍然显示页面而不是调试页面。
复制(使用firefox): 步骤进行:
实际结果:"糟糕,看起来出了问题"页面显示。 预期结果:仍显示登录页面,然后传递错误“#34;令牌不匹配"什么的。
请注意,当我清除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在这里工作的吗?
答案 0 :(得分:89)
您可以在 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);
}
}
答案 1 :(得分:14)
更好的 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);
}
我也非常喜欢这个想法:
答案 2 :(得分:11)
而不是尝试捕获异常只是将用户重定向回同一页面并让他/她重复操作。
在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.');
}
}
答案 3 :(得分: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();
}
}
答案 4 :(得分:1)
Laravel 8似乎在处理异常方面略有不同,并且上述解决方案在我全新安装的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.
}
});
}
}
答案 5 :(得分:0)
很好。 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.');
}
});