在 Laravel 中更改 CSRF 失败 HTTP 响应代码
Changing CSRF Failure HTTP Response Code in Laravel
我们通过 {{ csrf_field() }}
方法使用 laravel 5.3 的内置 csrf 保护。
当我们进行了 运行 次明显失败的安全扫描时,服务器返回 500 Internal Server Error
但这实际上不是服务器错误 - 因为它是客户端发送错误信息 - 因此它应该属于 400 错误范围。
我做了一些挖掘,但不太清楚 returns 500 的实际情况。
有人可以建议如何将此响应更改为其他内容吗?
您可以像这样通过 App/Http/Middleware/VerifyCSRFToken.php
文件覆盖它:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken extends BaseVerifier {
public function handle($request, Closure $next) {
try {
return parent::handle($request, $next);
} catch (TokenMismatchException $ex) {
// throw custom exception like so: throw new CustomException($ex->getMessage());
// or new HttpException with response code like so: abort(403, $ex->getMessage());
}
}
}
在 Laravel 5.3 中,您转到 app/Exceptions/Handler.php
并编辑 render()
函数。
public function render($request, Exception $exception)
{
if ($exception instanceof TokenMismatchException) {
//do some stuff here.
}
return parent::render($request, $exception);
}
我们通过 {{ csrf_field() }}
方法使用 laravel 5.3 的内置 csrf 保护。
当我们进行了 运行 次明显失败的安全扫描时,服务器返回 500 Internal Server Error
但这实际上不是服务器错误 - 因为它是客户端发送错误信息 - 因此它应该属于 400 错误范围。
我做了一些挖掘,但不太清楚 returns 500 的实际情况。
有人可以建议如何将此响应更改为其他内容吗?
您可以像这样通过 App/Http/Middleware/VerifyCSRFToken.php
文件覆盖它:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
use Illuminate\Session\TokenMismatchException;
class VerifyCsrfToken extends BaseVerifier {
public function handle($request, Closure $next) {
try {
return parent::handle($request, $next);
} catch (TokenMismatchException $ex) {
// throw custom exception like so: throw new CustomException($ex->getMessage());
// or new HttpException with response code like so: abort(403, $ex->getMessage());
}
}
}
在 Laravel 5.3 中,您转到 app/Exceptions/Handler.php
并编辑 render()
函数。
public function render($request, Exception $exception)
{
if ($exception instanceof TokenMismatchException) {
//do some stuff here.
}
return parent::render($request, $exception);
}