Passed
Pull Request — master (#18)
by Alexander
01:12
created

HttpBasic::getAuthenticationCredentials()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 25
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 25
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Auth\Method;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Yiisoft\Auth\AuthenticationMethodInterface;
10
use Yiisoft\Auth\IdentityInterface;
11
use Yiisoft\Auth\IdentityRepositoryInterface;
12
13
/**
14
 * HttpBasic supports the HTTP Basic authentication method.
15
 *
16
 * In case authentication does not work like expected, make sure your web server passes
17
 * username and password to `$request->getServerParams()['PHP_AUTH_USER']` and `$request->getServerParams()['PHP_AUTH_PW']`
18
 * variables. If you are using Apache with PHP-CGI, you might need to add this line to your `.htaccess` file:
19
 *
20
 * ```
21
 * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
22
 * ```
23
 */
24
final class HttpBasic implements AuthenticationMethodInterface
25
{
26
    /**
27
     * @var string the HTTP authentication realm
28
     */
29
    private string $realm = 'api';
30
    /**
31
     * @var callable a PHP callable that will authenticate the user with the HTTP basic auth information.
32
     * The callable receives a username and a password as its parameters. It should return an identity object
33
     * that matches the username and password. Null should be returned if there is no such identity.
34
     * The callable will be called only if current user is not authenticated.
35
     *
36
     * If this property is not set, the username information will be considered as an access token
37
     * while the password information will be ignored. The {@see \Yiisoft\Auth\IdentityRepositoryInterface::findIdentityByToken()}
38
     * method will be called to authenticate an identity.
39
     */
40
    private $authenticationCallback;
41
42
    private IdentityRepositoryInterface $identityRepository;
43
44 10
    public function __construct(IdentityRepositoryInterface $identityRepository)
45
    {
46 10
        $this->identityRepository = $identityRepository;
47 10
    }
48
49 8
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
50
    {
51 8
        [$username, $password] = $this->getAuthenticationCredentials($request);
52
53
54 8
        if ($this->authenticationCallback && ($username !== null || $password !== null)) {
55 2
            return \call_user_func($this->authenticationCallback, $username, $password);
56
        }
57
58 6
        if ($username !== null) {
59 4
            return $this->identityRepository->findIdentityByToken($username, get_class($this));
60
        }
61
62 2
        return null;
63
    }
64
65 2
    public function challenge(ResponseInterface $response): ResponseInterface
66
    {
67 2
        return $response->withHeader('WWW-Authenticate', "Basic realm=\"{$this->realm}\"");
68
    }
69
70 2
    public function withAuthenticationCallback(callable $authenticationCallback): self
71
    {
72 2
        $new = clone $this;
73 2
        $new->authenticationCallback = $authenticationCallback;
74 2
        return $new;
75
    }
76
77 1
    public function withRealm(string $realm): self
78
    {
79 1
        $new = clone $this;
80 1
        $new->realm = $realm;
81 1
        return $new;
82
    }
83
84
    /**
85
     * Obtains authentication credentials from request.
86
     *
87
     * @param ServerRequestInterface $request
88
     * @return array ['username', 'password'] array.
89
     */
90 8
    private function getAuthenticationCredentials(ServerRequestInterface $request): array
91
    {
92 8
        $username = $request->getServerParams()['PHP_AUTH_USER'] ?? null;
93 8
        $password = $request->getServerParams()['PHP_AUTH_PW'] ?? null;
94 8
        if ($username !== null || $password !== null) {
95 4
            return [$username, $password];
96
        }
97
98
        /*
99
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
100
         * To make it work, add the following line to to your .htaccess file:
101
         *
102
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
103
         */
104 4
        $token = $this->getTokenFromHeaders($request);
105 4
        if ($token !== null && $this->isBasicToken($token)) {
106 3
            $credentials = $this->extractCredentialsFromHeader($token);
107 3
            if (\count($credentials) < 2) {
108 1
                return [$credentials[0], null];
109
            }
110
111 2
            return $credentials;
112
        }
113
114 1
        return [null, null];
115
    }
116
117 4
    private function getTokenFromHeaders(ServerRequestInterface $request): ?string
118
    {
119 4
        $header = $request->getHeaderLine('Authorization');
120 4
        if (!empty($header)) {
121 2
            return $header;
122
        }
123
124 2
        return $request->getServerParams()['REDIRECT_HTTP_AUTHORIZATION'] ?? null;
125
    }
126
127 3
    private function extractCredentialsFromHeader(string $authToken): array
128
    {
129 3
        return array_map(
130 3
            fn ($value) => $value === '' ? null : $value,
131 3
            explode(':', base64_decode(mb_substr($authToken, 6)), 2)
132
        );
133
    }
134
135 3
    private function isBasicToken(string $token): bool
136
    {
137 3
        return strncasecmp($token, 'basic', 5) === 0;
138
    }
139
}
140