How to create CSRF token for Cakephp 3 PHPunit tes

2020-04-28 11:02发布

问题:

I am trying to get my unit tests working again after enabling CSRF tokens and SSL in my CakePHP 3 app.

How do I create or generate a token for a test like the following? Or do I just disable it for testing purposes?

public function testLogin() {
    $this->get('/login');
    $this->assertResponseOk();

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

    $this->assertResponseSuccess();
    $this->assertRedirect(['controller' => 'Users', 'action' => 'dashboard']);
}

回答1:

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!']);
}


回答2:

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.