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