How to create CSRF token for Cakephp 3 PHPunit testing?

给你一囗甜甜゛ 提交于 2019-12-01 22:53:30
Genar

The official documentation has good approach since version 3.1.2.

You only have to call $this->enableCsrfToken(); and/or $this->enableSecurityToken(); before your post to be able to perform the request successfully with token.

As the official example shows:

public function testAdd()
{
    $this->enableCsrfToken();
    $this->enableSecurityToken();
    $this->post('/posts/add', ['title' => 'Exciting news!']);
}

Just set the token in a cookie via ControllerIntergrationTestCase::cookie(), and also pass it via the POST data. By default the cookie name to use is csrfToken, and the POST data key has to be _csrfToken.

CSRF Tokens do not need to use any specific format, the CSRF component will only test the strings for equality.

$token = 'my-csrf-token';

$this->cookie('csrfToken', $token);

$data = [
    'email' => 'info@example.com',
    'password' => 'secret',
    '_csrfToken' => $token
];
$this->post('/login', $data);

Note that the cookies are kept until teardown, ie. each subquent request in the current test will use the configured cookies.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!