From 0f9fda14f7b82b932d1b4e1f76d4c17ec4996170 Mon Sep 17 00:00:00 2001 From: TiaNex Date: Sun, 6 Oct 2024 12:20:12 +0800 Subject: [PATCH] Update CsrfMiddleware.php use csrf trait and rename parameterName to formParameterName for the view injection also use parameterName --- src/CsrfMiddleware.php | 35 +++++------------------------------ 1 file changed, 5 insertions(+), 30 deletions(-) diff --git a/src/CsrfMiddleware.php b/src/CsrfMiddleware.php index cffab6c..e6671f3 100644 --- a/src/CsrfMiddleware.php +++ b/src/CsrfMiddleware.php @@ -11,6 +11,7 @@ use Psr\Http\Server\RequestHandlerInterface; use Yiisoft\Http\Method; use Yiisoft\Http\Status; +use Yiisoft\Csrf\CsrfTrait; use function in_array; use function is_string; @@ -21,12 +22,8 @@ * @link https://www.php-fig.org/psr/psr-15/ */ final class CsrfMiddleware implements MiddlewareInterface -{ - public const PARAMETER_NAME = '_csrf'; - public const HEADER_NAME = 'X-CSRF-Token'; - - private string $parameterName = self::PARAMETER_NAME; - private string $headerName = self::HEADER_NAME; +{ + use CsrfTrait; private ResponseFactoryInterface $responseFactory; private CsrfTokenInterface $token; @@ -59,29 +56,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface return $response; } - public function withParameterName(string $name): self - { - $new = clone $this; - $new->parameterName = $name; - return $new; - } - - public function withHeaderName(string $name): self - { - $new = clone $this; - $new->headerName = $name; - return $new; - } - - public function getParameterName(): string - { - return $this->parameterName; - } - - public function getHeaderName(): string - { - return $this->headerName; - } + private function validateCsrfToken(ServerRequestInterface $request): bool { @@ -98,7 +73,7 @@ private function getTokenFromRequest(ServerRequestInterface $request): ?string { $parsedBody = $request->getParsedBody(); - $token = $parsedBody[$this->parameterName] ?? null; + $token = $parsedBody[$this->formParameterName] ?? null; if (empty($token)) { $headers = $request->getHeader($this->headerName); $token = reset($headers);