-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathVerifierFactory.php
81 lines (67 loc) · 2.39 KB
/
VerifierFactory.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
<?php
namespace MiladRahimi\Jwt;
use InvalidArgumentException;
use MiladRahimi\Jwt\Base64\Base64Parser;
use MiladRahimi\Jwt\Base64\SafeBase64Parser;
use MiladRahimi\Jwt\Cryptography\Verifier;
use MiladRahimi\Jwt\Exceptions\InvalidTokenException;
use MiladRahimi\Jwt\Exceptions\JsonDecodingException;
use MiladRahimi\Jwt\Exceptions\NoKidException;
use MiladRahimi\Jwt\Exceptions\VerifierNotFoundException;
use MiladRahimi\Jwt\Json\JsonParser;
use MiladRahimi\Jwt\Json\StrictJsonParser;
class VerifierFactory
{
private array $verifiers;
private JsonParser $jsonParser;
private Base64Parser $base64Parser;
/**
* @param Verifier[] $verifiers
* @param JsonParser|null $jsonParser
* @param Base64Parser|null $base64Parser
*/
public function __construct(array $verifiers, JsonParser $jsonParser = null, Base64Parser $base64Parser = null)
{
foreach ($verifiers as $verifier) {
if ($verifier instanceof Verifier) {
$this->verifiers[$verifier->kid()] = $verifier;
} else {
throw new InvalidArgumentException(
'Values of $verifiers array must be instance of MiladRahimi\Jwt\Cryptography\Verifier.'
);
}
}
$this->jsonParser = $jsonParser ?: new StrictJsonParser();
$this->base64Parser = $base64Parser ?: new SafeBase64Parser();
}
/**
* @throws InvalidTokenException
* @throws JsonDecodingException
* @throws NoKidException
* @throws VerifierNotFoundException
*/
public function getVerifier(string $jwt): Verifier
{
$header = $this->jsonParser->decode($this->base64Parser->decode($this->extractHeader($jwt)));
if (isset($header['kid'])) {
if (isset($this->verifiers[$header['kid']])) {
return $this->verifiers[$header['kid']];
}
throw new VerifierNotFoundException("No verifier found for kid `{$header['kid']}`.");
}
throw new NoKidException();
}
/**
* Extract header component of given JWT
*
* @throws Exceptions\InvalidTokenException
*/
private function extractHeader(string $jwt): string
{
$sections = explode('.', $jwt);
if (count($sections) !== 3) {
throw new Exceptions\InvalidTokenException('JWT format is not valid,');
}
return $sections[0];
}
}