-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathSignedCookieListener.php
92 lines (78 loc) · 2.76 KB
/
SignedCookieListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
/*
* This file is part of the Nelmio SecurityBundle.
*
* (c) Nelmio <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nelmio\SecurityBundle\EventListener;
use Nelmio\SecurityBundle\Signer;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
final class SignedCookieListener
{
use KernelEventForwardCompatibilityTrait;
private Signer $signer;
/**
* @var list<string>|true
*/
private $signedCookieNames;
/**
* @param list<string> $signedCookieNames
*/
public function __construct(Signer $signer, array $signedCookieNames)
{
$this->signer = $signer;
if (\in_array('*', $signedCookieNames, true)) {
$this->signedCookieNames = true;
} else {
$this->signedCookieNames = $signedCookieNames;
}
}
public function onKernelRequest(RequestEvent $e): void
{
if (!$this->isMainRequest($e)) {
return;
}
$request = $e->getRequest();
$names = true === $this->signedCookieNames ? $request->cookies->keys() : $this->signedCookieNames;
foreach ($names as $name) {
if ($request->cookies->has($name)) {
$cookie = $request->cookies->get($name);
if ($this->signer->verifySignedValue($cookie)) {
$request->cookies->set($name, $this->signer->getVerifiedRawValue($cookie));
} else {
$request->cookies->remove($name);
}
}
}
}
public function onKernelResponse(ResponseEvent $e): void
{
if (!$this->isMainRequest($e)) {
return;
}
$response = $e->getResponse();
foreach ($response->headers->getCookies() as $cookie) {
if ($cookie->getValue() && (true === $this->signedCookieNames || \in_array($cookie->getName(), $this->signedCookieNames, true))) {
$response->headers->removeCookie($cookie->getName(), $cookie->getPath(), $cookie->getDomain());
$signedCookie = new Cookie(
$cookie->getName(),
$this->signer->getSignedValue($cookie->getValue()),
$cookie->getExpiresTime(),
$cookie->getPath(),
$cookie->getDomain(),
$cookie->isSecure(),
$cookie->isHttpOnly(),
$cookie->isRaw(),
$cookie->getSameSite()
);
$response->headers->setCookie($signedCookie);
}
}
}
}