Skip to content

Commit faae2d5

Browse files
Update XsrfMiddleware.php (#777)
As described here: #776 (comment), I couldn't get the XsrfMiddleware to work. Debugging extensively, I found two issues: 1) My front-end (Angular / httpClient) wasn't able to detect the XSRF-TOKEN Cookie, because its "path" value was not "/". Because of that, it did not send the X-XSRF-TOKEN Header. Setting the Cookie "path" value to "/" via XsrfMiddleware/getToken solved this problem. 2) When sending X-XSRF-TOKEN: 9aead2ceb0e150e1 in the Header, $request->getHeader($headerName) returns an Array ( [0] => 9aead2ceb0e150e1 ) - at least in my test cases. So "$token != $request->getHeader($headerName)" was always false. Changing the condition to "$token != $request->getHeader($headerName)[0]" solved this problem. Tested with Mozilla Firefox 86.0.1 and Google Chrome Version 89.0.4389.72 (both on Linux). Of course, I don't know if these changes have any unwanted side effects or will work in all environments.
1 parent 6d96185 commit faae2d5

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

src/Tqdev/PhpCrudApi/Middleware/XsrfMiddleware.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ private function getToken(): string
2020
$secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
2121
$token = bin2hex(random_bytes(8));
2222
if (!headers_sent()) {
23-
setcookie($cookieName, $token, 0, '', '', $secure);
23+
setcookie($cookieName, $token, 0, '/', '', $secure);
2424
}
2525
}
2626
return $token;
@@ -33,7 +33,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
3333
$excludeMethods = $this->getArrayProperty('excludeMethods', 'OPTIONS,GET');
3434
if (!in_array($method, $excludeMethods)) {
3535
$headerName = $this->getProperty('headerName', 'X-XSRF-TOKEN');
36-
if ($token != $request->getHeader($headerName)) {
36+
if ($token != $request->getHeader($headerName)[0]) {
3737
return $this->responder->error(ErrorCode::BAD_OR_MISSING_XSRF_TOKEN, '');
3838
}
3939
}

0 commit comments

Comments
 (0)