|
| 1 | +<?php |
| 2 | +/* |
| 3 | + * (c) Minh Vuong <vuongxuongminh@gmail.com> |
| 4 | + * |
| 5 | + * This source file is subject to the MIT license that is bundled |
| 6 | + * with this source code in the file LICENSE. |
| 7 | + */ |
| 8 | + |
| 9 | +declare(strict_types=1); |
| 10 | + |
| 11 | +namespace Istio\JWTPayloadExtractor; |
| 12 | + |
| 13 | +use Symfony\Component\HttpFoundation\HeaderBag; |
| 14 | +use Symfony\Component\HttpFoundation\InputBag; |
| 15 | +use Symfony\Component\HttpFoundation\Request; |
| 16 | + |
| 17 | +abstract class AbstractExtractor implements ExtractorInterface |
| 18 | +{ |
| 19 | + private string $requestBag; |
| 20 | + |
| 21 | + private string $itemName; |
| 22 | + |
| 23 | + private string $issuer; |
| 24 | + |
| 25 | + public function __construct( |
| 26 | + string $issuer, |
| 27 | + string $requestBag, |
| 28 | + string $itemName |
| 29 | + ) { |
| 30 | + if ('' === $issuer) { |
| 31 | + throw new \LogicException('Issuer can not be blank!'); |
| 32 | + } |
| 33 | + |
| 34 | + $this->issuer = $issuer; |
| 35 | + $this->requestBag = $requestBag; |
| 36 | + $this->itemName = $itemName; |
| 37 | + } |
| 38 | + |
| 39 | + final public function extract(Request $request): ?array |
| 40 | + { |
| 41 | + /** @var InputBag|HeaderBag $bag */ |
| 42 | + $bag = $request->{$this->requestBag}; |
| 43 | + $value = $bag->get($this->itemName); |
| 44 | + |
| 45 | + if (null === $value) { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + $payload = $this->extractFromValue($value); |
| 50 | + |
| 51 | + if (null === $payload || $this->issuer !== ($payload['iss'] ?? null)) { |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + return $payload; |
| 56 | + } |
| 57 | + |
| 58 | + abstract protected function extractFromValue(mixed $value): ?array; |
| 59 | + |
| 60 | + final protected function extractFromBase64EncodedPayload(string $encodedPayload): ?array |
| 61 | + { |
| 62 | + $jsonPayload = base64_decode($encodedPayload, true); |
| 63 | + |
| 64 | + if (false === $jsonPayload) { |
| 65 | + return null; |
| 66 | + } |
| 67 | + |
| 68 | + $payload = json_decode($jsonPayload, true); |
| 69 | + |
| 70 | + if (null === $payload) { |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + return $payload; |
| 75 | + } |
| 76 | +} |
0 commit comments