Skip to content

Commit

Permalink
Keep CSRF tokens consistent across all requests in a test case.
Browse files Browse the repository at this point in the history
Keep the CSRF token consistent across all the requests in a single test
case method. This saves regenerating the token and even lets people
pre-configure the token if they really want to.

Refs #7828
  • Loading branch information
markstory committed Dec 12, 2015
1 parent 1404250 commit cf833c7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/TestSuite/IntegrationTestCase.php
Expand Up @@ -430,12 +430,11 @@ protected function _addTokens($url, $data)
}

if ($this->_csrfToken === true) {
$csrfToken = Text::uuid();
if (!isset($data['_csrfToken'])) {
$data['_csrfToken'] = $csrfToken;
}
if (!isset($this->_cookie['csrfToken'])) {
$this->_cookie['csrfToken'] = $csrfToken;
$this->_cookie['csrfToken'] = Text::uuid();
}
if (!isset($data['_csrfToken'])) {
$data['_csrfToken'] = $this->_cookie['csrfToken'];
}
}
return $data;
Expand Down
33 changes: 33 additions & 0 deletions tests/TestCase/TestSuite/IntegrationTestCaseTest.php
Expand Up @@ -97,6 +97,39 @@ public function testRequestBuildingCsrfTokens()
$this->assertSame('fale', $request->data['_csrfToken']);
}

/**
* Test multiple actions using CSRF tokens don't fail
*
* @return void
*/
public function testEnableCsrfMultipleRequests()
{
$this->enableCsrfToken();
$first = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
$second = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'Second post']);
$this->assertSame($first->cookies['csrfToken'], $second->data['_csrfToken'], 'Csrf token should match cookie');
$this->assertSame(
$first->data['_csrfToken'],
$second->data['_csrfToken'],
'Tokens should be consistent per test method'
);
}

/**
* Test pre-determined CSRF tokens.
*
* @return void
*/
public function testEnableCsrfPredeterminedCookie()
{
$this->enableCsrfToken();
$value = 'I am a teapot';
$this->cookie('csrfToken', $value);
$request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
$this->assertSame($value, $request->cookies['csrfToken'], 'Csrf token should match cookie');
$this->assertSame($value, $request->data['_csrfToken'], 'Tokens should match');
}

/**
* Test building a request, with query parameters
*
Expand Down

0 comments on commit cf833c7

Please sign in to comment.