|
1
|
|
|
<?php |
|
2
|
|
|
namespace Yiisoft\Yii\Web\Auth; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Container\ContainerInterface; |
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Yiisoft\Yii\Web\User\IdentityInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* CompositeAuth allows multiple authentication methods at the same time. |
|
11
|
|
|
* |
|
12
|
|
|
* The authentication methods contained by CompositeAuth are configured via {@see setAuthMethods()}, |
|
13
|
|
|
* which is a list of supported authentication class configurations. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class CompositeAuth implements AuthInterface |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var AuthInterface[] |
|
19
|
|
|
*/ |
|
20
|
|
|
private $authMethods = []; |
|
21
|
|
|
/** |
|
22
|
|
|
* @var ContainerInterface |
|
23
|
|
|
*/ |
|
24
|
|
|
private $container; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct(ContainerInterface $container) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->container = $container; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function authenticate(ServerRequestInterface $request): ?IdentityInterface |
|
32
|
|
|
{ |
|
33
|
|
|
foreach ($this->authMethods as $i => $auth) { |
|
34
|
|
|
if (!$auth instanceof AuthInterface) { |
|
35
|
|
|
$this->authMethods[$i] = $auth = $this->container->get($auth); |
|
36
|
|
|
if (!$auth instanceof AuthInterface) { |
|
37
|
|
|
throw new \RuntimeException(get_class($auth) . ' must implement ' . AuthInterface::class); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$identity = $auth->authenticate($request); |
|
42
|
|
|
if ($identity !== null) { |
|
43
|
|
|
return $identity; |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return null; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function challenge(ResponseInterface $response): ResponseInterface |
|
51
|
|
|
{ |
|
52
|
|
|
foreach ($this->authMethods as $method) { |
|
53
|
|
|
$response = $method->challenge($response); |
|
54
|
|
|
} |
|
55
|
|
|
return $response; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function setAuthMethods(array $methods): void |
|
59
|
|
|
{ |
|
60
|
|
|
$this->authMethods = $methods; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|