如何在Laravel测试的获取路由中包含CSRF令牌?



为了防止CSRF攻击,我将一个带有当前CSRF令牌的状态参数添加到外部链接中。当外部页面将用户重定向回我的网站时,它将包含状态。

通过一个简单的条件,我可以在我的控制器中检查它:

if($data['state'] !== csrf_token()){
throw new TokenMismatchException;
}

现在我想为它编写一个测试以通过 if 条件,但 csrf_token(( 在测试目录中为空,但在控制器中不为空。所以不幸的是,它失败了。以下是测试的摘录:

/** @test */
public function it_saves_the_data_in_database() 
{
$this->get(route('connect.index', [
'scope' => $this->scope,
'code' => $this->code,
'state' => csrf_token(), //it's null here...
]))->assertStatus(200); //however it returns 419
}

之前是否可以生成令牌?

如果您在使用 crsf_token(( 之前编写了 HTTP 访问测试代码,如以下示例所示。

csrf 令牌似乎是在该测试会话中生成的。

$this->get(...)
$this->get(route('connect.index', [
'scope' => $this->scope,
'code' => $this->code,
'state' => csrf_token(), //it's null here...
]))->assertStatus(200);

最新更新