Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Signature/JWSLoader.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Signature;
6
7 use Exception;
8 use Jose\Component\Checker\HeaderCheckerManager;
9 use Jose\Component\Core\JWK;
10 use Jose\Component\Core\JWKSet;
11 use Jose\Component\Signature\Serializer\JWSSerializerManager;
12 use Throwable;
13
14 /**
15 * @see \Jose\Tests\Component\Signature\JWSLoaderTest
16 */
17 class JWSLoader
18 {
19 public function __construct(
20 private readonly JWSSerializerManager $serializerManager,
21 private readonly JWSVerifier $jwsVerifier,
22 private readonly ?HeaderCheckerManager $headerCheckerManager
23 ) {
24 }
25
26 /**
27 * Returns the JWSVerifier associated to the JWSLoader.
28 */
29 public function getJwsVerifier(): JWSVerifier
30 {
31 return $this->jwsVerifier;
32 }
33
34 /**
35 * Returns the Header Checker Manager associated to the JWSLoader.
36 */
37 public function getHeaderCheckerManager(): ?HeaderCheckerManager
38 {
39 return $this->headerCheckerManager;
40 }
41
42 /**
43 * Returns the JWSSerializer associated to the JWSLoader.
44 */
45 public function getSerializerManager(): JWSSerializerManager
46 {
47 return $this->serializerManager;
48 }
49
50 /**
51 * This method will try to load and verify the token using the given key. It returns a JWS and will populate the
52 * $signature variable in case of success, otherwise an exception is thrown.
53 */
54 public function loadAndVerifyWithKey(string $token, JWK $key, ?int &$signature, ?string $payload = null): JWS
55 {
56 $keyset = new JWKSet([$key]);
57
58 return $this->loadAndVerifyWithKeySet($token, $keyset, $signature, $payload);
59 }
60
61 /**
62 * This method will try to load and verify the token using the given key set. It returns a JWS and will populate the
63 * $signature variable in case of success, otherwise an exception is thrown.
64 */
65 public function loadAndVerifyWithKeySet(
66 string $token,
67 JWKSet $keyset,
68 ?int &$signature,
69 ?string $payload = null
70 ): JWS {
71 try {
72 $jws = $this->serializerManager->unserialize($token);
73 $nbSignatures = $jws->countSignatures();
74 for ($i = 0; $i < $nbSignatures; ++$i) {
75 if ($this->processSignature($jws, $keyset, $i, $payload)) {
76 $signature = $i;
77
78 return $jws;
79 }
80 }
81 } catch (Throwable) {
82 // Nothing to do. Exception thrown just after
83 }
84
85 throw new Exception('Unable to load and verify the token.');
86 }
87
88 private function processSignature(JWS $jws, JWKSet $keyset, int $signature, ?string $payload): bool
89 {
90 try {
91 if ($this->headerCheckerManager !== null) {
92 $this->headerCheckerManager->check($jws, $signature);
93 }
94
95 return $this->jwsVerifier->verifyWithKeySet($jws, $keyset, $signature, $payload);
96 } catch (Throwable) {
97 return false;
98 }
99 }
100 }