diff --git a/src/CsrfMiddleware.php b/src/CsrfMiddleware.php index cffab6c..38d2a2e 100644 --- a/src/CsrfMiddleware.php +++ b/src/CsrfMiddleware.php @@ -27,6 +27,7 @@ final class CsrfMiddleware implements MiddlewareInterface private string $parameterName = self::PARAMETER_NAME; private string $headerName = self::HEADER_NAME; + private bool $parseBody = true; private ResponseFactoryInterface $responseFactory; private CsrfTokenInterface $token; @@ -73,6 +74,13 @@ public function withHeaderName(string $name): self return $new; } + public function withParseBody(bool $parseBody): self + { + $new = clone $this; + $new->parseBody = $parseBody; + return $new; + } + public function getParameterName(): string { return $this->parameterName; @@ -83,6 +91,11 @@ public function getHeaderName(): string return $this->headerName; } + public function getParseBody(): bool + { + return $this->parseBody; + } + private function validateCsrfToken(ServerRequestInterface $request): bool { if (in_array($request->getMethod(), [Method::GET, Method::HEAD, Method::OPTIONS], true)) { @@ -96,12 +109,12 @@ private function validateCsrfToken(ServerRequestInterface $request): bool private function getTokenFromRequest(ServerRequestInterface $request): ?string { - $parsedBody = $request->getParsedBody(); + $headers = $request->getHeader($this->headerName); + $token = reset($headers); - $token = $parsedBody[$this->parameterName] ?? null; - if (empty($token)) { - $headers = $request->getHeader($this->headerName); - $token = reset($headers); + if (empty($token) && $this->parseBody) { + $parsedBody = $request->getParsedBody(); + $token = $parsedBody[$this->parameterName] ?? null; } return is_string($token) ? $token : null; diff --git a/src/EmptyCsrfToken.php b/src/EmptyCsrfToken.php new file mode 100644 index 0000000..7d7ebce --- /dev/null +++ b/src/EmptyCsrfToken.php @@ -0,0 +1,21 @@ +