【问题标题】:How do I enable VerifyCsrfToken for some tests?如何为某些测试启用 VerifyCsrfToken?
【发布时间】:2017-04-07 16:13:00
【问题描述】:
如果运行测试,Laravel 默认为 disables VerifyCsrfToken 中间件。结果我没有注意到 api 路由需要 csrf 令牌才能成功。有没有办法在某些测试中启用它?喜欢
function withVerifyCsrfTokenMiddleware()
{
$this->app... // here we're passing something to the app
}
并在VerifyCsrfToken的handle方法中进行修改。在一个定制的。一个,覆盖框架中的方法。但这只是我的想法。有更好的吗?
【问题讨论】:
标签:
php
laravel
automated-tests
csrf-protection
【解决方案1】:
好的,这就是我所做的:
app/Http/Middleware/VerifyCsrfToken.php:
function handle($request, Closure $next)
{
$dontSkipCsrfVerificationWhenRunningTests
= $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
&& $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
if (
$this->isReading($request) ||
! $dontSkipCsrfVerificationWhenRunningTests && $this->runningUnitTests() ||
$this->shouldPassThrough($request) ||
$this->tokensMatch($request)
) {
return $this->addCookieToResponse($request, $next($request));
}
throw new TokenMismatchException;
}
tests/TestCase.php:
function withVerifyCsrfTokenMiddleware()
{
$this->app->instance('dontSkipCsrfVerificationWhenRunningTests', TRUE);
}
【解决方案2】:
对上述答案的小改动,而不是更改句柄方法,我更新了 runningUnitTests 方法以减少升级时出现问题的机会:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
];
/**
* Determine if the application is running unit tests.
*
* @return bool
*/
protected function runningUnitTests()
{
$dontSkip
= $this->app->bound('dontSkipCsrfVerificationWhenRunningTests')
&& $this->app->make('dontSkipCsrfVerificationWhenRunningTests');
return $this->app->runningInConsole() && $this->app->runningUnitTests() && !$dontSkip;
}
}