|
1
|
|
|
<?php |
|
2
|
|
|
namespace Yiisoft\Yii\Web\Auth; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
6
|
|
|
use Yiisoft\Yii\Web\User\IdentityInterface; |
|
7
|
|
|
use Yiisoft\Yii\Web\User\IdentityRepositoryInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* HttpHeaderAuth is an action filter that supports HTTP authentication through HTTP Headers. |
|
11
|
|
|
* |
|
12
|
|
|
* The default implementation of HttpHeaderAuth uses the [[Yiisoft\Yii\Web\User\IdentityRepositoryInterface::findIdentityByToken()|findIdentityByToken()]] |
|
13
|
|
|
* method of the `user` application component and passes the value of the `X-Api-Key` header. This implementation is used |
|
14
|
|
|
* for authenticating API clients. |
|
15
|
|
|
*/ |
|
16
|
|
|
final class HttpBearerAuth implements AuthInterface |
|
17
|
|
|
{ |
|
18
|
|
|
use HttpHeaderAuthTrait; |
|
19
|
|
|
private const HEADER_NAME = 'Authorization'; |
|
20
|
|
|
private const PATTERN = '/^Bearer\s+(.*?)$/'; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var string the HTTP authentication realm |
|
24
|
|
|
*/ |
|
25
|
|
|
private $realm = 'api'; |
|
26
|
|
|
/** |
|
27
|
|
|
* @var IdentityRepositoryInterface |
|
28
|
|
|
*/ |
|
29
|
|
|
private $identityRepository; |
|
30
|
|
|
|
|
31
|
|
|
public function __construct(IdentityRepositoryInterface $identityRepository) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->identityRepository = $identityRepository; |
|
34
|
|
|
$this->header = self::HEADER_NAME; |
|
35
|
|
|
$this->pattern = self::PATTERN; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function authenticate(ServerRequestInterface $request): ?IdentityInterface |
|
39
|
|
|
{ |
|
40
|
|
|
$authToken = $this->getAuthToken($request); |
|
41
|
|
|
if ($authToken !== null) { |
|
42
|
|
|
|
|
43
|
|
|
return $this->identityRepository->findIdentityByToken($authToken, get_class($this)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
return null; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public function challenge(ResponseInterface $response): ResponseInterface |
|
50
|
|
|
{ |
|
51
|
|
|
return $response->withHeader('WWW-Authenticate', "{$this->header} realm=\"{$this->realm}\""); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function setRealm(string $realm): void |
|
55
|
|
|
{ |
|
56
|
|
|
$this->realm = $realm; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|