1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EcPhp\ApiGwAuthenticationBundle\Service\KeyLoader; |
6
|
|
|
|
7
|
|
|
use EcPhp\ApiGwAuthenticationBundle\Exception\ApiGwAuthenticationException; |
8
|
|
|
use EcPhp\ApiGwAuthenticationBundle\Service\KeyConverter\KeyConverterInterface; |
9
|
|
|
use Symfony\Contracts\HttpClient\HttpClientInterface; |
10
|
|
|
use Throwable; |
11
|
|
|
|
12
|
|
|
use function array_key_exists; |
13
|
|
|
|
14
|
|
|
final class JWKSKeyLoader implements KeyLoaderInterface |
15
|
|
|
{ |
16
|
|
|
private HttpClientInterface $httpClient; |
17
|
|
|
|
18
|
|
|
private KeyConverterInterface $keyConverter; |
19
|
|
|
|
20
|
|
|
private KeyLoaderInterface $keyLoader; |
21
|
|
|
|
22
|
12 |
|
public function __construct( |
23
|
|
|
KeyLoaderInterface $keyLoader, |
24
|
|
|
HttpClientInterface $httpClient, |
25
|
|
|
KeyConverterInterface $keyConverter |
26
|
|
|
) { |
27
|
12 |
|
$this->keyLoader = $keyLoader; |
28
|
12 |
|
$this->httpClient = $httpClient; |
29
|
12 |
|
$this->keyConverter = $keyConverter; |
30
|
12 |
|
} |
31
|
|
|
|
32
|
1 |
|
public function getPassphrase(): string |
33
|
|
|
{ |
34
|
1 |
|
return $this->keyLoader->getPassphrase(); |
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
public function getPublicKey(): string |
38
|
|
|
{ |
39
|
1 |
|
return $this->keyLoader->getPublicKey(); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
public function getSigningKey(): string |
43
|
|
|
{ |
44
|
1 |
|
return $this->keyLoader->getSigningKey(); |
45
|
|
|
} |
46
|
|
|
|
47
|
11 |
|
public function loadKey($type): string |
48
|
|
|
{ |
49
|
|
|
// Todo: Implements for PRIVATE key as well. |
50
|
11 |
|
$key = $this->keyLoader->getPublicKey(); |
51
|
|
|
|
52
|
|
|
try { |
53
|
11 |
|
$response = $this->httpClient->request('GET', $key); |
54
|
4 |
|
} catch (Throwable $e) { |
55
|
4 |
|
throw new ApiGwAuthenticationException( |
56
|
4 |
|
sprintf('Unable to request uri(%s) for %s key.', $key, $type), |
57
|
4 |
|
$e->getCode(), |
58
|
|
|
$e |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
|
62
|
7 |
|
if (200 !== $statusCode = $response->getStatusCode()) { |
63
|
2 |
|
throw new ApiGwAuthenticationException( |
64
|
2 |
|
sprintf('Invalid code(%s) thrown while fetching the %s key at %s.', $statusCode, $type, $key) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
5 |
|
$jwks = $response->toArray(); |
69
|
|
|
|
70
|
5 |
|
if (false === array_key_exists('keys', $jwks)) { |
71
|
1 |
|
throw new ApiGwAuthenticationException( |
72
|
1 |
|
sprintf('Invalid JWKS format of %s key at %s.', $type, $key) |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
4 |
|
if ([] === $jwks['keys']) { |
77
|
1 |
|
throw new ApiGwAuthenticationException( |
78
|
1 |
|
sprintf('Invalid JWKS format of %s key at %s, keys array is empty.', $type, $key) |
79
|
|
|
); |
80
|
|
|
} |
81
|
|
|
|
82
|
3 |
|
return current($this->keyConverter->fromJWKStoPEMS($jwks['keys'])); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|