Skip to content

Commit 09e37bf

Browse files
author
Greg Bowler
committed
feature: ignore url from csrf protection
for #389
1 parent f3840f2 commit 09e37bf

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

config.default.ini

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,5 @@ query_path=query
5050
[security]
5151
;default_headers="X-Content-Type-Options: nosniff; X-Frame-Options: deny; Content-Security-Policy: default-src 'none'"
5252
csrf_header=X-CSRF
53+
;csrf_ignore_path=/test-csrf-ignore,/test/*/wildcard/,/another-test-ignore
54+
csrf_ignore_path=

src/Middleware/RequestHandler.php

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,13 +201,33 @@ public function handle(
201201
$session->getStore("webengine.csrf", true)
202202
);
203203

204-
if($request->getMethod() === "POST") {
205-
$csrfTokenStore->verify($_POST);
204+
$shouldVerifyCsrf = true;
205+
$ignoredPathArray = explode(",", $this->config->getString("security.csrf_ignore_path") ?? "");
206+
foreach($ignoredPathArray as $ignoredPath) {
207+
if(str_contains($ignoredPath, "*")) {
208+
$pattern = strtr(rtrim($ignoredPath, "/"), [
209+
"*" => ".*",
210+
]);
211+
if(preg_match("|$pattern|", rtrim($uriPath, "/"))) {
212+
$shouldVerifyCsrf = false;
213+
}
214+
}
215+
else {
216+
if(rtrim($uriPath, "/") === rtrim($ignoredPath, "/")) {
217+
$shouldVerifyCsrf = false;
218+
}
219+
}
206220
}
207221

208-
$protector = new HTMLDocumentProtector($viewModel, $csrfTokenStore);
209-
$tokens = $protector->protect(HTMLDocumentProtector::ONE_TOKEN_PER_FORM);
210-
$response = $response->withHeader($this->config->getString("security.csrf_header"), $tokens);
222+
if($shouldVerifyCsrf) {
223+
if($request->getMethod() === "POST") {
224+
$csrfTokenStore->verify($_POST);
225+
}
226+
227+
$protector = new HTMLDocumentProtector($viewModel, $csrfTokenStore);
228+
$tokens = $protector->protect(HTMLDocumentProtector::ONE_TOKEN_PER_FORM);
229+
$response = $response->withHeader($this->config->getString("security.csrf_header"), $tokens);
230+
}
211231
}
212232

213233
$input = new Input($_GET, $_POST, $_FILES);

0 commit comments

Comments
 (0)