Skip to content

Commit

Permalink
Support X-CSRF-Token header
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Oct 29, 2023
1 parent f28207e commit b398de7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/main/php/web/frontend/Frontend.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ private function view($req, $res, $delegate, $matches= []) {
}

// Verify CSRF token for anything which is not a GET or HEAD request
if (!isset($CSRF_EXEMPT[strtolower($req->method())]) && $req->value('token') !== $req->param('token')) {
$token= $req->param('token') ?? $req->header('X-CSRF-Token');
if (!isset($CSRF_EXEMPT[strtolower($req->method())]) && $req->value('token') !== $token) {
return $this->errors()->handle(new Error(403, 'Incorrect CSRF token for '.$delegate->name()));
}

Expand Down
12 changes: 9 additions & 3 deletions src/test/php/web/frontend/unittest/CSRFTokenTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@ public function write($template, $context, $out) { /* NOOP */ }
* @param string $method
* @param string $uri
* @param ?string $payload
* @param [:string] $headers
* @return void
* @throws web.Error
*/
private function execute($method, $uri, $payload= null) {
$headers= $payload ? ['Content-Type' => 'application/x-www-form-urlencoded'] : [];
private function execute($method, $uri, $payload= null, $headers= []) {
$payload && $headers['Content-Type']= 'application/x-www-form-urlencoded';

$req= new Request(new TestInput($method, $uri, $headers, (string)$payload));
$res= new Response(new TestOutput());
Expand All @@ -37,10 +38,15 @@ private function execute($method, $uri, $payload= null) {
}

#[Test]
public function validated() {
public function validated_as_part_of_payload() {
$this->execute('POST', '/users', 'token='.self::TOKEN.'&username=test');
}

#[Test]
public function validated_as_header() {
$this->execute('POST', '/users', 'username=test', ['X-CSRF-Token' => self::TOKEN]);
}

#[Test]
public function not_validated_for_get_requests() {
$this->execute('GET', '/users');
Expand Down

0 comments on commit b398de7

Please sign in to comment.