diff --git a/SameOriginCsrfTokenManager.php b/SameOriginCsrfTokenManager.php index 0c95208..b1e0730 100644 --- a/SameOriginCsrfTokenManager.php +++ b/SameOriginCsrfTokenManager.php @@ -207,9 +207,17 @@ public function clearCookies(Request $request, Response $response): void public function persistStrategy(Request $request): void { - if ($request->hasSession(true) && $request->attributes->has($this->cookieName)) { - $request->getSession()->set($this->cookieName, $request->attributes->get($this->cookieName)); + if (!$request->attributes->has($this->cookieName) + || !$request->hasSession(true) + || !($session = $request->getSession())->isStarted() + ) { + return; } + + $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : 0; + $usageIndexReference = \PHP_INT_MIN; + $session->set($this->cookieName, $request->attributes->get($this->cookieName)); + $usageIndexReference = $usageIndexValue; } public function onKernelResponse(ResponseEvent $event): void diff --git a/Tests/SameOriginCsrfTokenManagerTest.php b/Tests/SameOriginCsrfTokenManagerTest.php index eae31de..0a215d2 100644 --- a/Tests/SameOriginCsrfTokenManagerTest.php +++ b/Tests/SameOriginCsrfTokenManagerTest.php @@ -221,9 +221,11 @@ public function testClearCookies() $this->assertTrue($response->headers->has('Set-Cookie')); } - public function testPersistStrategyWithSession() + public function testPersistStrategyWithStartedSession() { $session = $this->createMock(Session::class); + $session->method('isStarted')->willReturn(true); + $request = new Request(); $request->setSession($session); $request->attributes->set('csrf-token', 2 << 8); @@ -233,6 +235,19 @@ public function testPersistStrategyWithSession() $this->csrfTokenManager->persistStrategy($request); } + public function testPersistStrategyWithSessionNotStarted() + { + $session = $this->createMock(Session::class); + + $request = new Request(); + $request->setSession($session); + $request->attributes->set('csrf-token', 2 << 8); + + $session->expects($this->never())->method('set'); + + $this->csrfTokenManager->persistStrategy($request); + } + public function testOnKernelResponse() { $request = new Request([], [], ['csrf-token' => 2], ['csrf-token_test' => 'csrf-token']);