-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathKeycloak.php
391 lines (345 loc) · 10.3 KB
/
Keycloak.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
namespace Stevenmaguire\OAuth2\Client\Provider;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use Psr\Http\Message\ResponseInterface;
use Stevenmaguire\OAuth2\Client\Provider\Exception\EncryptionConfigurationException;
use UnexpectedValueException;
class Keycloak extends AbstractProvider
{
use BearerAuthorizationTrait;
/**
* Keycloak URL, eg. http://localhost:8080/auth.
*
* @var string
*/
public $authServerUrl = null;
/**
* Realm name, eg. demo.
*
* @var string
*/
public $realm = null;
/**
* Encryption algorithm.
*
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*
* @var string
*/
public $encryptionAlgorithm = null;
/**
* Encryption key.
*
* @var string
*/
public $encryptionKey = null;
/**
* Keycloak version.
*
* @var string
*/
public $version = null;
/**
* Constructs an OAuth 2.0 service provider.
*
* @param array $options An array of options to set on this provider.
* Options include `clientId`, `clientSecret`, `redirectUri`, and `state`.
* Individual providers may introduce more options, as needed.
* @param array $collaborators An array of collaborators that may be used to
* override this provider's default behavior. Collaborators include
* `grantFactory`, `requestFactory`, `httpClient`, and `randomFactory`.
* Individual providers may introduce more collaborators, as needed.
*/
public function __construct(array $options = [], array $collaborators = [])
{
if (isset($options['encryptionKeyPath'])) {
$this->setEncryptionKeyPath($options['encryptionKeyPath']);
unset($options['encryptionKeyPath']);
}
if (isset($options['version'])) {
$this->setVersion($options['version']);
}
parent::__construct($options, $collaborators);
}
/**
* Attempts to decrypt the given response.
*
* @param string|array|null $response
*
* @return string|array|null
* @throws EncryptionConfigurationException
*/
public function decryptResponse($response)
{
if (!is_string($response)) {
return $response;
}
if ($this->usesEncryption()) {
return json_decode(
json_encode(
JWT::decode(
$response,
new Key(
$this->encryptionKey,
$this->encryptionAlgorithm
)
)
),
true
);
}
throw EncryptionConfigurationException::undeterminedEncryption();
}
/**
* Get authorization url to begin OAuth flow
*
* @return string
*/
public function getBaseAuthorizationUrl()
{
return $this->getBaseUrlWithRealm().'/protocol/openid-connect/auth';
}
/**
* Get access token url to retrieve token
*
* @param array $params
*
* @return string
*/
public function getBaseAccessTokenUrl(array $params)
{
return $this->getBaseUrlWithRealm().'/protocol/openid-connect/token';
}
/**
* Get provider url to fetch user details
*
* @param AccessToken $token
*
* @return string
*/
public function getResourceOwnerDetailsUrl(AccessToken $token)
{
return $this->getBaseUrlWithRealm().'/protocol/openid-connect/userinfo';
}
/**
* Builds the logout URL.
*
* @param array $options
* @return string Authorization URL
*/
public function getLogoutUrl(array $options = [])
{
$base = $this->getBaseLogoutUrl();
$params = $this->getAuthorizationParameters($options);
// Starting with keycloak 18.0.0, the parameter redirect_uri is no longer supported on logout.
// As of this version the parameter is called post_logout_redirect_uri. In addition to this
// a parameter id_token_hint has to be provided.
if ($this->validateGteVersion('18.0.0')) {
if (isset($options['access_token']) === true) {
$accessToken = $options['access_token'];
$params['id_token_hint'] = $accessToken->getValues()['id_token'];
$params['post_logout_redirect_uri'] = $params['redirect_uri'];
}
unset($params['redirect_uri']);
}
$query = $this->getAuthorizationQuery($params);
return $this->appendQuery($base, $query);
}
/**
* Get logout url to logout of session token
*
* @return string
*/
private function getBaseLogoutUrl()
{
return $this->getBaseUrlWithRealm() . '/protocol/openid-connect/logout';
}
/**
* Creates base url from provider configuration.
*
* @return string
*/
protected function getBaseUrlWithRealm()
{
return $this->authServerUrl.'/realms/'.$this->realm;
}
/**
* Get the default scopes used by this provider.
*
* This should not be a complete list of all scopes, but the minimum
* required for the provider user interface!
*
* @return string[]
*/
protected function getDefaultScopes()
{
$scopes = [
'profile',
'email'
];
if ($this->validateGteVersion('20.0.0')) {
$scopes[] = 'openid';
}
return $scopes;
}
/**
* Returns the string that should be used to separate scopes when building
* the URL for requesting an access token.
*
* @return string Scope separator, defaults to ','
*/
protected function getScopeSeparator()
{
return ' ';
}
/**
* Check a provider response for errors.
*
* @throws IdentityProviderException
* @param ResponseInterface $response
* @param string $data Parsed response data
* @return void
*/
protected function checkResponse(ResponseInterface $response, $data)
{
if (!empty($data['error'])) {
$error = $data['error'];
if (isset($data['error_description'])) {
$error .= ': '.$data['error_description'];
}
throw new IdentityProviderException($error, $response->getStatusCode(), $data);
}
}
/**
* Generate a user object from a successful user details request.
*
* @param array $response
* @param AccessToken $token
* @return KeycloakResourceOwner
*/
protected function createResourceOwner(array $response, AccessToken $token)
{
return new KeycloakResourceOwner($response);
}
/**
* Requests and returns the resource owner of given access token.
*
* @param AccessToken $token
* @return KeycloakResourceOwner
* @throws EncryptionConfigurationException
*/
public function getResourceOwner(AccessToken $token)
{
$response = $this->fetchResourceOwnerDetails($token);
// We are always getting an array. We have to check if it is
// the array we created
if (array_key_exists('jwt', $response)) {
$response = $response['jwt'];
}
$response = $this->decryptResponse($response);
return $this->createResourceOwner($response, $token);
}
/**
* Updates expected encryption algorithm of Keycloak instance.
*
* @param string $encryptionAlgorithm
*
* @return Keycloak
*/
public function setEncryptionAlgorithm($encryptionAlgorithm)
{
$this->encryptionAlgorithm = $encryptionAlgorithm;
return $this;
}
/**
* Updates expected encryption key of Keycloak instance.
*
* @param string $encryptionKey
*
* @return Keycloak
*/
public function setEncryptionKey($encryptionKey)
{
$this->encryptionKey = $encryptionKey;
return $this;
}
/**
* Updates expected encryption key of Keycloak instance to content of given
* file path.
*
* @param string $encryptionKeyPath
*
* @return Keycloak
*/
public function setEncryptionKeyPath($encryptionKeyPath)
{
try {
$this->encryptionKey = file_get_contents($encryptionKeyPath);
} catch (Exception $e) {
// Not sure how to handle this yet.
}
return $this;
}
/**
* Updates the keycloak version.
*
* @param string $version
*
* @return Keycloak
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Checks if provider is configured to use encryption.
*
* @return bool
*/
public function usesEncryption()
{
return (bool) $this->encryptionAlgorithm && $this->encryptionKey;
}
/**
* Parses the response according to its content-type header.
*
* @throws UnexpectedValueException
* @param ResponseInterface $response
* @return array
*/
protected function parseResponse(ResponseInterface $response)
{
// We have a problem with keycloak when the userinfo responses
// with a jwt token
// Because it just return a jwt as string with the header
// application/jwt
// This can't be parsed to a array
// Dont know why this function only allow an array as return value...
$content = (string) $response->getBody();
$type = $this->getContentType($response);
if (strpos($type, 'jwt') !== false) {
// Here we make the temporary array
return ['jwt' => $content];
}
return parent::parseResponse($response);
}
/**
* Validate if version is greater or equal
*
* @param string $version
* @return bool
*/
private function validateGteVersion($version)
{
return (isset($this->version) && version_compare($this->version, $version, '>='));
}
}