forked from fschmtt/keycloak-rest-api-client-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
109 lines (95 loc) · 3.29 KB
/
Copy pathClient.php
File metadata and controls
109 lines (95 loc) · 3.29 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace Fschmtt\Keycloak\Http;
use DateTime;
use Fschmtt\Keycloak\Keycloak;
use Fschmtt\Keycloak\OAuth\TokenStorageInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Token;
use Psr\Http\Message\ResponseInterface;
/**
* @internal
*/
class Client
{
public function __construct(
private readonly Keycloak $keycloak,
private readonly ClientInterface $httpClient,
private readonly TokenStorageInterface $tokenStorage,
) {}
/**
* @param array<string, mixed> $options
*/
public function request(string $method, string $path = '', array $options = []): ResponseInterface
{
if (!$this->isAuthorized()) {
$this->authorize();
}
$defaultOptions = [
'base_uri' => $this->keycloak->getBaseUrl(),
'headers' => [
'Authorization' => 'Bearer ' . $this->tokenStorage->retrieveAccessToken()->toString(),
],
];
$options = array_merge_recursive($options, $defaultOptions);
return $this->httpClient->request(
$method,
$this->keycloak->getBaseUrl() . $path,
$options,
);
}
public function isAuthorized(): bool
{
return $this->tokenStorage->retrieveAccessToken()?->isExpired(new DateTime()) === false;
}
private function authorize(): void
{
$tokens = $this->fetchTokens();
$parser = (new Token\Parser(new JoseEncoder()));
$this->tokenStorage->storeAccessToken($parser->parse($tokens['access_token']));
$this->tokenStorage->storeRefreshToken($parser->parse($tokens['refresh_token']));
}
/**
* @return array{access_token: non-empty-string, refresh_token: non-empty-string}
*/
private function fetchTokens(): array
{
try {
$response = $this->httpClient->request(
'POST',
$this->keycloak->getBaseUrl() . '/realms/' . $this->keycloak->getRealm() . '/protocol/openid-connect/token',
[
'form_params' => [
'refresh_token' => $this->tokenStorage->retrieveRefreshToken()?->toString(),
'client_id' => 'admin-cli',
'grant_type' => 'refresh_token',
],
],
);
} catch (ClientException $e) {
$response = $this->httpClient->request(
'POST',
$this->keycloak->getBaseUrl() . '/realms/' . $this->keycloak->getRealm() . '/protocol/openid-connect/token',
[
'form_params' => [
'username' => $this->keycloak->getUsername(),
'password' => $this->keycloak->getPassword(),
'client_id' => 'admin-cli',
'grant_type' => 'password',
],
],
);
}
$tokens = json_decode(
$response->getBody()->getContents(),
true,
flags: JSON_THROW_ON_ERROR,
);
return [
'access_token' => $tokens['access_token'],
'refresh_token' => $tokens['refresh_token'],
];
}
}