From 6dc93436a658ff608ec22cf3e7b3102b12df7403 Mon Sep 17 00:00:00 2001 From: tamcy Date: Fri, 19 Feb 2021 12:13:03 +0800 Subject: [PATCH] [HttpKernel] Configure `session.cookie_secure` earlier --- EventListener/SessionListener.php | 16 +++++++++++++--- Tests/EventListener/SessionListenerTest.php | 8 ++++++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/EventListener/SessionListener.php b/EventListener/SessionListener.php index a53ade797c..6cff47b88d 100644 --- a/EventListener/SessionListener.php +++ b/EventListener/SessionListener.php @@ -14,6 +14,7 @@ use Psr\Container\ContainerInterface; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; +use Symfony\Component\HttpKernel\Event\GetResponseEvent; /** * Sets the session in the request. @@ -33,10 +34,12 @@ public function __construct(ContainerInterface $container) $this->container = $container; } - protected function getSession(): ?SessionInterface + public function onKernelRequest(GetResponseEvent $event) { - if (!$this->container->has('session')) { - return null; + parent::onKernelRequest($event); + + if (!$event->isMasterRequest() || !$this->container->has('session')) { + return; } if ($this->container->has('session_storage') @@ -46,6 +49,13 @@ protected function getSession(): ?SessionInterface ) { $storage->setOptions(['cookie_secure' => true]); } + } + + protected function getSession(): ?SessionInterface + { + if (!$this->container->has('session')) { + return null; + } return $this->container->get('session'); } diff --git a/Tests/EventListener/SessionListenerTest.php b/Tests/EventListener/SessionListenerTest.php index de1069606b..e0dba81683 100644 --- a/Tests/EventListener/SessionListenerTest.php +++ b/Tests/EventListener/SessionListenerTest.php @@ -59,7 +59,7 @@ public function testSessionIsSet() $listener = new SessionListener($container); $event = $this->createMock(RequestEvent::class); - $event->expects($this->once())->method('isMasterRequest')->willReturn(true); + $event->expects($this->exactly(2))->method('isMasterRequest')->willReturn(true); $event->expects($this->once())->method('getRequest')->willReturn($request); $listener->onKernelRequest($event); @@ -203,12 +203,16 @@ public function testGetSessionIsCalledOnce() $listener = new SessionListener($container); $listener->onKernelRequest($event); + // storage->setOptions() should have been called already + $container->set('session_storage', null); + $sessionStorage = null; + $subRequest = $masterRequest->duplicate(); // at this point both master and subrequest have a closure to build the session $masterRequest->getSession(); - // calling the factory on the subRequest should not trigger a second call to storage->sesOptions() + // calling the factory on the subRequest should not trigger a second call to storage->setOptions() $subRequest->getSession(); } }