|
6 | 6 |
|
7 | 7 | use DateTime; |
8 | 8 | use Fschmtt\Keycloak\Keycloak; |
| 9 | +use Fschmtt\Keycloak\OAuth\GrantType; |
9 | 10 | use Fschmtt\Keycloak\OAuth\GrantType\RefreshToken; |
10 | 11 | use Fschmtt\Keycloak\OAuth\TokenStorageInterface; |
11 | 12 | use GuzzleHttp\ClientInterface; |
|
18 | 19 | */ |
19 | 20 | class Client |
20 | 21 | { |
| 22 | + private GrantType $grantType; |
| 23 | + |
21 | 24 | public function __construct( |
22 | 25 | private readonly Keycloak $keycloak, |
23 | 26 | private readonly ClientInterface $httpClient, |
24 | 27 | private readonly TokenStorageInterface $tokenStorage, |
25 | | - ) {} |
| 28 | + ) { |
| 29 | + if ($grantType = $this->keycloak->getGrantType()) { |
| 30 | + $this->grantType = $grantType; |
| 31 | + } else { |
| 32 | + $this->grantType = GrantType::password( |
| 33 | + // @phpstan-ignore method.deprecated |
| 34 | + $this->keycloak->getUsername() ?? throw new \InvalidArgumentException('Username must be provided'), |
| 35 | + // @phpstan-ignore method.deprecated |
| 36 | + $this->keycloak->getPassword() ?? throw new \InvalidArgumentException('Password must be provided'), |
| 37 | + 'admin-cli', |
| 38 | + // @phpstan-ignore method.deprecated |
| 39 | + $this->keycloak->getRealm() ?? throw new \InvalidArgumentException('Realm must be provided'), |
| 40 | + ); |
| 41 | + } |
| 42 | + } |
26 | 43 |
|
27 | 44 | /** |
28 | 45 | * @param array<string, mixed> $options |
@@ -70,25 +87,25 @@ private function fetchTokens(): array |
70 | 87 | { |
71 | 88 | if ($refreshToken = $this->tokenStorage->retrieveRefreshToken()) { |
72 | 89 | $refreshTokenGrantType = new RefreshToken( |
73 | | - $this->keycloak->getGrantType()->clientId, |
| 90 | + $this->grantType->clientId, |
74 | 91 | $refreshToken->toString(), |
75 | | - $this->keycloak->getGrantType()->clientSecret, |
76 | | - $this->keycloak->getGrantType()->scope, |
| 92 | + $this->grantType->clientSecret, |
| 93 | + $this->grantType->scope, |
77 | 94 | ); |
78 | 95 |
|
79 | 96 | $response = $this->httpClient->request( |
80 | 97 | 'POST', |
81 | | - $this->keycloak->getBaseUrl() . '/realms/' . $this->keycloak->getGrantType()->realm . '/protocol/openid-connect/token', |
| 98 | + $this->keycloak->getBaseUrl() . '/realms/' . $this->grantType->realm . '/protocol/openid-connect/token', |
82 | 99 | [ |
83 | 100 | 'form_params' => $refreshTokenGrantType->toRequestParams(), |
84 | 101 | ], |
85 | 102 | ); |
86 | 103 | } else { |
87 | 104 | $response = $this->httpClient->request( |
88 | 105 | 'POST', |
89 | | - $this->keycloak->getBaseUrl() . '/realms/' . $this->keycloak->getGrantType()->realm . '/protocol/openid-connect/token', |
| 106 | + $this->keycloak->getBaseUrl() . '/realms/' . $this->grantType->realm . '/protocol/openid-connect/token', |
90 | 107 | [ |
91 | | - 'form_params' => $this->keycloak->getGrantType()->toRequestParams(), |
| 108 | + 'form_params' => $this->grantType->toRequestParams(), |
92 | 109 | ], |
93 | 110 | ); |
94 | 111 | } |
|
0 commit comments