-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBasicAuthorizationService.php
More file actions
99 lines (82 loc) · 2.78 KB
/
BasicAuthorizationService.php
File metadata and controls
99 lines (82 loc) · 2.78 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
<?php
namespace PhpMiddleware\HttpAuthentication;
use PhpMiddleware\HttpAuthentication\CredentialAdapter\UserPasswordInterface;
use Psr\Http\Message\ServerRequestInterface;
use UnexpectedValueException;
final class BasicAuthorizationService implements AuthorizationServiceInterface
{
const AUTHORIZATION_HEADER = 'Authorization';
const SCHEME = 'Basic';
/**
* @var UserPasswordInterface
*/
protected $adapter;
/**
* @var string
*/
protected $realm;
/**
* @param UserPasswordInterface $adapter
* @param string $realm
*/
public function __construct(UserPasswordInterface $adapter, $realm)
{
$this->adapter = $adapter;
$this->realm = (string) $realm;
}
/**
* @param ServerRequestInterface $request
*
* @return AuthorizationResultInterface
*
* @throws UnexpectedValueException
*/
public function authorize(ServerRequestInterface $request)
{
$header = $request->getHeaderLine(self::AUTHORIZATION_HEADER);
list($userId, $password) = $this->findCredentialsFromHeader($header);
if ($userId && $password) {
$result = $this->adapter->authenticate($userId, $password);
if ($result === true) {
return AuthorizationResult::authorized(self::SCHEME, [], ['user-ID' => $userId]);
} elseif ($result === false) {
return AuthorizationResult::error(self::SCHEME, 'Invalid credentials', 'Login and/or password are invalid', [
'realm' => $this->realm,
]);
}
throw new UnexpectedValueException(sprintf('%s\'s result must be a boolean value', UserPasswordInterface::class));
}
return AuthorizationResult::error(self::SCHEME, 'Invalid header', 'Cannot read user-ID and password from header', [
'realm' => $this->realm,
]);
}
/**
* @param string $header
*
* @return array|null
*/
private function findCredentialsFromHeader($header)
{
$matches = [];
$userPass = $this->findBasicDecodedUserPassString($header);
if (is_string($userPass) && preg_match('/^(?<userID>[0-9a-zA-Z]+):(?<password>[0-9a-zA-Z]+)$/', $userPass, $matches) === 1) {
return [
$matches['userID'],
$matches['password']
];
}
}
/**
* @param string $header
*
* @return string|null
*/
private function findBasicDecodedUserPassString($header)
{
$matches = [];
if (preg_match('/^Basic (?<base64>(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)$/', $header, $matches) === 1) {
$base64 = $matches['base64'];
return base64_decode($base64);
}
}
}