-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathAuthenticationService.php
510 lines (457 loc) · 16.7 KB
/
AuthenticationService.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 1.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Authentication;
use ArrayAccess;
use Authentication\Authenticator\AuthenticatorCollection;
use Authentication\Authenticator\AuthenticatorInterface;
use Authentication\Authenticator\ImpersonationInterface;
use Authentication\Authenticator\PersistenceInterface;
use Authentication\Authenticator\ResultInterface;
use Authentication\Authenticator\StatelessInterface;
use Authentication\Identifier\IdentifierCollection;
use Authentication\Identifier\IdentifierInterface;
use Cake\Core\InstanceConfigTrait;
use Cake\Routing\Router;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
/**
* Authentication Service
*/
class AuthenticationService implements AuthenticationServiceInterface, ImpersonationInterface
{
use InstanceConfigTrait;
/**
* Authenticator collection
*
* @var \Authentication\Authenticator\AuthenticatorCollection|null
*/
protected ?AuthenticatorCollection $_authenticators = null;
/**
* Identifier collection
*
* @var \Authentication\Identifier\IdentifierCollection|null
*/
protected ?IdentifierCollection $_identifiers = null;
/**
* Authenticator that successfully authenticated the identity.
*
* @var \Authentication\Authenticator\AuthenticatorInterface|null
*/
protected ?AuthenticatorInterface $_successfulAuthenticator = null;
/**
* Result of the last authenticate() call.
*
* @var \Authentication\Authenticator\ResultInterface|null
*/
protected ?ResultInterface $_result = null;
/**
* Default configuration
*
* - `authenticators` - An array of authentication objects to use for authenticating users.
* You can configure multiple adapters and they will be checked sequentially
* when users are identified.
* - `identifiers` - An array of identifiers. The identifiers are constructed by the service
* and then passed to the authenticators that will pass the credentials to them and get the
* user data.
* - `identityClass` - The class name of identity or a callable identity builder.
* - `identityAttribute` - The request attribute used to store the identity. Default to `identity`.
* - `unauthenticatedRedirect` - The URL to redirect unauthenticated errors to. See
* AuthenticationComponent::allowUnauthenticated()
* - `queryParam` - The name of the query string parameter containing the previously blocked URL
* in case of unauthenticated redirect, or null to disable appending the denied URL.
*
* ### Example:
*
* ```
* $service = new AuthenticationService([
* 'authenticators' => [
* 'Authentication.Form
* ],
* 'identifiers' => [
* 'Authentication.Password'
* ]
* ]);
* ```
*
* @var array
*/
protected array $_defaultConfig = [
'authenticators' => [],
'identifiers' => [],
'identityClass' => Identity::class,
'identityAttribute' => 'identity',
'queryParam' => null,
'unauthenticatedRedirect' => null,
];
/**
* Constructor
*
* @param array $config Configuration options.
*/
public function __construct(array $config = [])
{
$this->setConfig($config);
}
/**
* Access the identifier collection
*
* @return \Authentication\Identifier\IdentifierCollection
*/
public function identifiers(): IdentifierCollection
{
if ($this->_identifiers === null) {
$this->_identifiers = new IdentifierCollection($this->getConfig('identifiers'));
}
return $this->_identifiers;
}
/**
* Access the authenticator collection
*
* @return \Authentication\Authenticator\AuthenticatorCollection
*/
public function authenticators(): AuthenticatorCollection
{
if ($this->_authenticators === null) {
$identifiers = $this->identifiers();
$authenticators = $this->getConfig('authenticators');
$this->_authenticators = new AuthenticatorCollection($identifiers, $authenticators);
}
return $this->_authenticators;
}
/**
* Loads an authenticator.
*
* @param string $name Name or class name.
* @param array $config Authenticator configuration.
* @return \Authentication\Authenticator\AuthenticatorInterface
*/
public function loadAuthenticator(string $name, array $config = []): AuthenticatorInterface
{
return $this->authenticators()->load($name, $config);
}
/**
* Loads an identifier.
*
* @param string $name Name or class name.
* @param array $config Identifier configuration.
* @return \Authentication\Identifier\IdentifierInterface Identifier instance
*/
public function loadIdentifier(string $name, array $config = []): IdentifierInterface
{
return $this->identifiers()->load($name, $config);
}
/**
* {@inheritDoc}
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @return \Authentication\Authenticator\ResultInterface The result object. If none of the adapters was a success
* the last failed result is returned.
* @throws \RuntimeException Throws a runtime exception when no authenticators are loaded.
*/
public function authenticate(ServerRequestInterface $request): ResultInterface
{
$result = null;
/** @var \Authentication\Authenticator\AuthenticatorInterface $authenticator */
foreach ($this->authenticators() as $authenticator) {
$result = $authenticator->authenticate($request);
if ($result->isValid()) {
$this->_successfulAuthenticator = $authenticator;
return $this->_result = $result;
}
if ($authenticator instanceof StatelessInterface) {
$authenticator->unauthorizedChallenge($request);
}
}
if ($result === null) {
throw new RuntimeException(
'No authenticators loaded. You need to load at least one authenticator.',
);
}
$this->_successfulAuthenticator = null;
return $this->_result = $result;
}
/**
* Clears the identity from authenticators that store them and the request
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Message\ResponseInterface $response The response.
* @return array Return an array containing the request and response objects.
* @return array{request: \Psr\Http\Message\ServerRequestInterface, response: \Psr\Http\Message\ResponseInterface}
*/
public function clearIdentity(ServerRequestInterface $request, ResponseInterface $response): array
{
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
if ($authenticator instanceof ImpersonationInterface && $authenticator->isImpersonating($request)) {
$stopImpersonationResult = $authenticator->stopImpersonating($request, $response);
['request' => $request, 'response' => $response] = $stopImpersonationResult;
}
$result = $authenticator->clearIdentity($request, $response);
['request' => $request, 'response' => $response] = $result;
}
}
$this->_successfulAuthenticator = null;
return [
'request' => $request->withoutAttribute($this->getConfig('identityAttribute')),
'response' => $response,
];
}
/**
* Sets identity data and persists it in the authenticators that support it.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Message\ResponseInterface $response The response.
* @param \ArrayAccess|array $identity Identity data.
* @return array{request: \Psr\Http\Message\ServerRequestInterface, response: \Psr\Http\Message\ResponseInterface}
*/
public function persistIdentity(
ServerRequestInterface $request,
ResponseInterface $response,
ArrayAccess|array $identity,
): array {
foreach ($this->authenticators() as $authenticator) {
if ($authenticator instanceof PersistenceInterface) {
$result = $authenticator->persistIdentity($request, $response, $identity);
$request = $result['request'];
$response = $result['response'];
}
}
$identity = $this->buildIdentity($identity);
return [
'request' => $request->withAttribute($this->getConfig('identityAttribute'), $identity),
'response' => $response,
];
}
/**
* Gets the successful authenticator instance if one was successful after calling authenticate.
*
* @return \Authentication\Authenticator\AuthenticatorInterface|null
*/
public function getAuthenticationProvider(): ?AuthenticatorInterface
{
return $this->_successfulAuthenticator;
}
/**
* Convenient method to gets the successful identifier instance.
*
* @return \Authentication\Identifier\IdentifierInterface|null
*/
public function getIdentificationProvider(): ?IdentifierInterface
{
return $this->identifiers()->getIdentificationProvider();
}
/**
* Gets the result of the last authenticate() call.
*
* @return \Authentication\Authenticator\ResultInterface|null Authentication result interface
*/
public function getResult(): ?ResultInterface
{
return $this->_result;
}
/**
* Gets an identity object
*
* @return \Authentication\IdentityInterface|null
*/
public function getIdentity(): ?IdentityInterface
{
if ($this->_result === null) {
return null;
}
$identityData = $this->_result->getData();
if (!$this->_result->isValid() || $identityData === null) {
return null;
}
return $this->buildIdentity($identityData);
}
/**
* Return the name of the identity attribute.
*
* @return string
*/
public function getIdentityAttribute(): string
{
return $this->getConfig('identityAttribute');
}
/**
* Builds the identity object
*
* @param \ArrayAccess|array $identityData Identity data
* @return \Authentication\IdentityInterface
*/
public function buildIdentity(ArrayAccess|array $identityData): IdentityInterface
{
if ($identityData instanceof IdentityInterface) {
return $identityData;
}
$class = $this->getConfig('identityClass');
if (is_callable($class)) {
$identity = $class($identityData);
} else {
$identity = new $class($identityData);
}
if (!($identity instanceof IdentityInterface)) {
throw new RuntimeException(sprintf(
'Object `%s` does not implement `%s`',
get_class($identity),
IdentityInterface::class,
));
}
return $identity;
}
/**
* Return the URL to redirect unauthenticated users to.
*
* If the `unauthenticatedRedirect` option is not set,
* this method will return null.
*
* If the `queryParam` option is set a query parameter
* will be appended with the denied URL path.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request
* @return string|null
*/
public function getUnauthenticatedRedirectUrl(ServerRequestInterface $request): ?string
{
$param = $this->getConfig('queryParam');
$target = $this->getConfig('unauthenticatedRedirect');
if ($target === null) {
return null;
}
if (is_array($target)) {
$target = Router::url($target);
}
if ($param === null) {
return $target;
}
$uri = $request->getUri();
$redirect = $uri->getPath();
if ($uri->getQuery()) {
$redirect .= '?' . $uri->getQuery();
}
$query = urlencode($param) . '=' . urlencode($redirect);
/** @var array $url */
$url = parse_url($target);
if (isset($url['query']) && strlen($url['query'])) {
$url['query'] .= '&' . $query;
} else {
$url['query'] = $query;
}
$fragment = isset($url['fragment']) ? '#' . $url['fragment'] : '';
$url['path'] = $url['path'] ?? '/';
return $url['path'] . '?' . $url['query'] . $fragment;
}
/**
* Return the URL that an authenticated user came from or null.
*
* This reads from the URL parameter defined in the `queryParam` option.
* Will return null if this parameter doesn't exist or is invalid.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request
* @return string|null
*/
public function getLoginRedirect(ServerRequestInterface $request): ?string
{
$redirectParam = $this->getConfig('queryParam');
$params = $request->getQueryParams();
if (
empty($redirectParam) ||
!isset($params[$redirectParam]) ||
strlen($params[$redirectParam]) === 0
) {
return null;
}
$parsed = parse_url($params[$redirectParam]);
if ($parsed === false) {
return null;
}
if (!empty($parsed['host']) || !empty($parsed['scheme'])) {
return null;
}
$parsed += ['path' => '/', 'query' => ''];
if (strlen($parsed['path']) && $parsed['path'][0] !== '/') {
$parsed['path'] = "/{$parsed['path']}";
}
if ($parsed['query']) {
$parsed['query'] = "?{$parsed['query']}";
}
return $parsed['path'] . $parsed['query'];
}
/**
* Impersonates a user
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request
* @param \Psr\Http\Message\ResponseInterface $response The response
* @param \ArrayAccess $impersonator User who impersonates
* @param \ArrayAccess $impersonated User impersonated
* @return array
*/
public function impersonate(
ServerRequestInterface $request,
ResponseInterface $response,
ArrayAccess $impersonator,
ArrayAccess $impersonated,
): array {
$provider = $this->getImpersonationProvider();
return $provider->impersonate($request, $response, $impersonator, $impersonated);
}
/**
* Stops impersonation
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request
* @param \Psr\Http\Message\ResponseInterface $response The response
* @return array
*/
public function stopImpersonating(ServerRequestInterface $request, ResponseInterface $response): array
{
$provider = $this->getImpersonationProvider();
return $provider->stopImpersonating($request, $response);
}
/**
* Returns true if impersonation is being done
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request
* @return bool
*/
public function isImpersonating(ServerRequestInterface $request): bool
{
$provider = $this->getImpersonationProvider();
return $provider->isImpersonating($request);
}
/**
* Get impersonation provider
*
* @return \Authentication\Authenticator\ImpersonationInterface
* @throws \InvalidArgumentException
*/
protected function getImpersonationProvider(): ImpersonationInterface
{
$provider = $this->getAuthenticationProvider();
if ($provider === null) {
throw new InvalidArgumentException('No AuthenticationProvider present.');
}
if (!($provider instanceof ImpersonationInterface)) {
$className = get_class($provider);
throw new InvalidArgumentException(
"The {$className} Provider must implement ImpersonationInterface in order to use impersonation.",
);
}
return $provider;
}
}