2016-06-09 19:27
浏览 46

Laravel PHPUnit总是通过CSRF

I'm currently writing a test to assure that our CSRF protection works in Laravel. The test looks like this.

public function testSecurityIncorrectCSRF()
     ->type('REDACTED', 'email')
     ->type('123123', 'password');



No matter what I do, and even if I pass a wrong _token, the login request will always succeed. I've tried outside of the PHPUnit test and there the CSRF protection works. All my middlewares are enabled, so the CSRF protection should be enabled.

Can anybody explain why this happens?

图片转代码服务由CSDN问答提供 功能建议

我正在编写一个测试,以确保我们的CSRF保护在Laravel中有效。 测试看起来像这样。

  public function testSecurityIncorrectCSRF()
 $ this-> visit('/ login')
  - > type(' 删除','电子邮件')
  - >类型('123123','密码'); 
会话() - > regenerateToken(); 
 $ this->按('登录 ')
  - > seePageIs('/ login'); 

无论我做什么,即使我传递错误的_token, 登录请求将始终成功。 我已经在PHPUnit测试之外尝试过,CSRF保护工作正常。 我的所有中间件都已启用,因此应启用CSRF保护。


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjianhe1388 2016-06-09 19:58

    Have a look at the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken class, especially the handle method.

    public function handle($request, Closure $next)
        if (
            $this->isReading($request) ||
            $this->runningUnitTests() ||
            $this->shouldPassThrough($request) ||
        ) {
            return $this->addCookieToResponse($request, $next($request));
        throw new TokenMismatchException;

    It always passes the csrf token check if it detects that the request comes from a unit test: $this->runningUnitTests()

    A solution would be to put the following code at the start of your test-function:

    $this->app['env'] = 'production';

    This will change the environment to production, thus enabling the csrf token check.

    解决 无用
    打赏 举报

相关推荐 更多相似问题