1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace example\components; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
8
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
9
|
|
|
use Zend\Diactoros\Response; |
10
|
|
|
|
11
|
|
|
class HttpBasicAuthMiddleware implements MiddlewareInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
private $users; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* HttpBasicAuthMiddleware constructor. |
20
|
|
|
* @param array $users |
21
|
|
|
*/ |
22
|
|
|
public function __construct(array $users) |
23
|
|
|
{ |
24
|
|
|
$this->users = $users; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param ServerRequestInterface $request |
29
|
|
|
* @param RequestHandlerInterface $handler |
30
|
|
|
* @return ResponseInterface |
31
|
|
|
*/ |
32
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
33
|
|
|
{ |
34
|
|
|
$login = $this->login($request); |
35
|
|
|
|
36
|
|
|
if (empty($login)) { |
37
|
|
|
$response = new Response('php://memory'); |
38
|
|
|
return $response->withStatus(401, 'Unauthorized')->withHeader('WWW-Authenticate', 'Basic realm="Test"'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$response = $handler->handle($request); |
42
|
|
|
|
43
|
|
|
return $response; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Check the user credentials and return the username or false. |
48
|
|
|
* |
49
|
|
|
* @param ServerRequestInterface $request |
50
|
|
|
* @return bool|mixed |
51
|
|
|
*/ |
52
|
|
|
private function login(ServerRequestInterface $request) |
53
|
|
|
{ |
54
|
|
|
//Check header |
55
|
|
|
$authorization = $this->parseHeader($request->getHeaderLine('Authorization')); |
56
|
|
|
|
57
|
|
|
if (!$authorization) { |
|
|
|
|
58
|
|
|
return false; |
59
|
|
|
} |
60
|
|
|
//Check the user |
61
|
|
|
if (!isset($this->users[$authorization['username']])) { |
62
|
|
|
return false; |
63
|
|
|
} |
64
|
|
|
if ($this->users[$authorization['username']] !== $authorization['password']) { |
65
|
|
|
return false; |
66
|
|
|
} |
67
|
|
|
return $authorization['username']; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Parses the authorization header for a basic authentication. |
72
|
|
|
* |
73
|
|
|
* @param string $header |
74
|
|
|
* @return array|bool |
75
|
|
|
*/ |
76
|
|
|
private function parseHeader(string $header) |
77
|
|
|
{ |
78
|
|
|
if (strpos($header, 'Basic') !== 0) { |
79
|
|
|
return false; |
80
|
|
|
} |
81
|
|
|
$header = explode(':', base64_decode(substr($header, 6)), 2); |
82
|
|
|
return [ |
83
|
|
|
'username' => $header[0], |
84
|
|
|
'password' => isset($header[1]) ? $header[1] : null, |
85
|
|
|
]; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|