-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathCookieAuthenticator.php
More file actions
251 lines (218 loc) · 7.9 KB
/
CookieAuthenticator.php
File metadata and controls
251 lines (218 loc) · 7.9 KB
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
<?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\Authenticator;
use ArrayAccess;
use Authentication\Identifier\IdentifierFactory;
use Authentication\Identifier\IdentifierInterface;
use Authentication\Identifier\PasswordIdentifier;
use Authentication\PasswordHasher\PasswordHasherTrait;
use Authentication\UrlChecker\UrlCheckerTrait;
use Cake\Http\Cookie\Cookie;
use Cake\Http\Cookie\CookieInterface;
use Cake\Utility\Security;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Cookie Authenticator
*
* Authenticates an identity based on a cookie data.
*/
class CookieAuthenticator extends AbstractAuthenticator implements PersistenceInterface
{
use PasswordHasherTrait;
use UrlCheckerTrait;
/**
* @inheritDoc
*/
protected array $_defaultConfig = [
'loginUrl' => null,
'urlChecker' => 'Authentication.Default',
'rememberMeField' => 'remember_me',
'fields' => [
PasswordIdentifier::CREDENTIAL_USERNAME => 'username',
PasswordIdentifier::CREDENTIAL_PASSWORD => 'password',
],
'cookie' => [
'name' => 'CookieAuth',
],
'passwordHasher' => 'Authentication.Default',
'salt' => true,
];
/**
* Gets the identifier, loading a default Password identifier if none configured.
*
* This is done lazily to allow configuration to be fully set before creating the identifier.
*
* @return \Authentication\Identifier\IdentifierInterface
*/
public function getIdentifier(): IdentifierInterface
{
if ($this->_identifier === null) {
$identifierConfig = [];
if ($this->getConfig('fields')) {
$identifierConfig['fields'] = $this->getConfig('fields');
}
$this->_identifier = IdentifierFactory::create('Authentication.Password', $identifierConfig);
}
return $this->_identifier;
}
/**
* @inheritDoc
*/
public function authenticate(ServerRequestInterface $request): ResultInterface
{
$cookies = $request->getCookieParams();
$cookieName = $this->getConfig('cookie.name');
if (!isset($cookies[$cookieName])) {
return new Result(null, Result::FAILURE_CREDENTIALS_MISSING, [
'Login credentials not found',
]);
}
if (is_array($cookies[$cookieName])) {
$token = $cookies[$cookieName];
} else {
$token = json_decode($cookies[$cookieName], true);
}
if ($token === null || count($token) !== 2) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID, [
'Cookie token is invalid.',
]);
}
[$username, $tokenHash] = $token;
$identifier = $this->getIdentifier();
$identity = $identifier->identify(compact('username'));
if (!$identity) {
return new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND, $identifier->getErrors());
}
if (!$this->_checkToken($identity, $tokenHash)) {
return new Result(null, Result::FAILURE_CREDENTIALS_INVALID, [
'Cookie token does not match',
]);
}
return new Result($identity, Result::SUCCESS);
}
/**
* @inheritDoc
*/
public function persistIdentity(
ServerRequestInterface $request,
ResponseInterface $response,
ArrayAccess|array $identity,
): array {
$field = $this->getConfig('rememberMeField');
$bodyData = $request->getParsedBody();
if (!$this->_checkUrl($request) || !is_array($bodyData) || empty($bodyData[$field])) {
return [
'request' => $request,
'response' => $response,
];
}
$value = $this->_createToken($identity);
$cookie = $this->_createCookie($value);
return [
'request' => $request,
'response' => $response->withAddedHeader('Set-Cookie', $cookie->toHeaderValue()),
];
}
/**
* Creates a plain part of a cookie token.
*
* Returns concatenated username, password hash, and HMAC signature.
*
* @param \ArrayAccess<string, mixed>|array<string, mixed> $identity Identity data.
* @return string
*/
protected function _createPlainToken(ArrayAccess|array $identity): string
{
$usernameField = $this->getConfig('fields.username');
$passwordField = $this->getConfig('fields.password');
if ($identity[$usernameField] === null || $identity[$passwordField] === null) {
throw new InvalidArgumentException(
sprintf('Fields %s cannot be found in entity', '`' . $usernameField . '`/`' . $passwordField . '`'),
);
}
$value = $identity[$usernameField] . $identity[$passwordField];
$salt = $this->getConfig('salt', '');
if ($salt === false) {
return $value;
}
if ($salt === true) {
$salt = Security::getSalt();
} elseif (!is_string($salt) || $salt === '') {
throw new InvalidArgumentException('Salt must be a non-empty string.');
}
$hmac = hash_hmac('sha1', $value, $salt);
// Instead of appending the plain salt, we create a hash. This limits the chance of the salt being leaked.
return $value . $hmac;
}
/**
* Creates a full cookie token serialized as a JSON sting.
*
* Cookie token consists of a username and hashed username + password hash.
*
* @param \ArrayAccess<string, mixed>|array<string, mixed> $identity Identity data.
* @return string
* @throws \JsonException
*/
protected function _createToken(ArrayAccess|array $identity): string
{
$plain = $this->_createPlainToken($identity);
$hash = $this->getPasswordHasher()->hash($plain);
$usernameField = $this->getConfig('fields.username');
return json_encode([$identity[$usernameField], $hash], JSON_THROW_ON_ERROR);
}
/**
* Checks whether a token hash matches the identity data.
*
* @param \ArrayAccess<string, mixed>|array<string, mixed> $identity Identity data.
* @param string $tokenHash Hashed part of a cookie token.
* @return bool
*/
protected function _checkToken(ArrayAccess|array $identity, string $tokenHash): bool
{
$plain = $this->_createPlainToken($identity);
return $this->getPasswordHasher()->check($plain, $tokenHash);
}
/**
* @inheritDoc
*/
public function clearIdentity(ServerRequestInterface $request, ResponseInterface $response): array
{
$cookie = $this->_createCookie('')->withExpired();
return [
'request' => $request,
'response' => $response->withAddedHeader('Set-Cookie', $cookie->toHeaderValue()),
];
}
/**
* Creates a cookie instance with configured defaults.
*
* @param mixed $value Cookie value.
* @return \Cake\Http\Cookie\CookieInterface
*/
protected function _createCookie(mixed $value): CookieInterface
{
$options = $this->getConfig('cookie');
$name = $options['name'];
unset($options['name']);
return Cookie::create(
$name,
$value,
$options,
);
}
}