1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MiladRahimi\Jwt; |
6
|
|
|
|
7
|
|
|
use MiladRahimi\Jwt\Base64\SafeBase64Parser; |
8
|
|
|
use MiladRahimi\Jwt\Base64\Base64Parser; |
9
|
|
|
use MiladRahimi\Jwt\Cryptography\Signer; |
10
|
|
|
use MiladRahimi\Jwt\Json\StrictJsonParser; |
11
|
|
|
use MiladRahimi\Jwt\Json\JsonParser; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Generator is responsible for crafting JSON Web Tokens (JWTs) |
15
|
|
|
* based on specified claims. |
16
|
|
|
*/ |
17
|
|
|
class Generator |
18
|
|
|
{ |
19
|
|
|
private Signer $signer; |
20
|
|
|
|
21
|
|
|
private JsonParser $jsonParser; |
22
|
|
|
|
23
|
|
|
private Base64Parser $base64Parser; |
24
|
|
|
|
25
|
|
|
public function __construct(Signer $signer, ?JsonParser $jsonParser = null, ?Base64Parser $base64Parser = null) |
26
|
|
|
{ |
27
|
|
|
$this->signer = $signer; |
28
|
|
|
$this->jsonParser = $jsonParser ?: new StrictJsonParser(); |
29
|
|
|
$this->base64Parser = $base64Parser ?: new SafeBase64Parser(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Generate JWT for the given claims |
34
|
|
|
* |
35
|
|
|
* @throws Exceptions\JsonEncodingException |
36
|
|
|
* @throws Exceptions\SigningException |
37
|
|
|
*/ |
38
|
|
|
public function generate(array $claims = []): string |
39
|
|
|
{ |
40
|
|
|
$header = $this->base64Parser->encode($this->jsonParser->encode($this->header())); |
41
|
|
|
$payload = $this->base64Parser->encode($this->jsonParser->encode($claims)); |
42
|
|
|
$signature = $this->base64Parser->encode($this->signer->sign("$header.$payload")); |
43
|
|
|
|
44
|
|
|
return join('.', [$header, $payload, $signature]); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Generate the JWT header |
49
|
|
|
*/ |
50
|
|
|
private function header(): array |
51
|
|
|
{ |
52
|
|
|
$header = ['typ' => 'JWT', 'alg' => $this->signer->name()]; |
53
|
|
|
if ($this->signer->kid() !== null) { |
54
|
|
|
$header['kid'] = $this->signer->kid(); |
55
|
|
|
} |
56
|
|
|
return $header; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getJsonParser(): JsonParser |
60
|
|
|
{ |
61
|
|
|
return $this->jsonParser; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getBase64Parser(): Base64Parser |
65
|
|
|
{ |
66
|
|
|
return $this->base64Parser; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function getSigner(): Signer |
70
|
|
|
{ |
71
|
|
|
return $this->signer; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|