1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace UMA\Psr7Hmac\Psr15; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use UMA\Psr7Hmac\Specification; |
12
|
|
|
use UMA\Psr7Hmac\Verifier; |
13
|
|
|
|
14
|
|
|
final class HmacMiddleware implements MiddlewareInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var KeyProviderInterface |
18
|
|
|
*/ |
19
|
|
|
private $keyProvider; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var SecretProviderInterface |
23
|
|
|
*/ |
24
|
|
|
private $secretProvider; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var RequestHandlerInterface |
28
|
|
|
*/ |
29
|
|
|
private $unauthenticatedHandler; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var Verifier |
33
|
|
|
*/ |
34
|
|
|
private $hmacVerifier; |
35
|
|
|
|
36
|
4 |
|
public function __construct( |
37
|
|
|
KeyProviderInterface $keyProvider, |
38
|
|
|
SecretProviderInterface $secretProvider, |
39
|
|
|
RequestHandlerInterface $unauthenticatedHandler |
40
|
|
|
) |
41
|
|
|
{ |
42
|
4 |
|
$this->keyProvider = $keyProvider; |
43
|
4 |
|
$this->secretProvider = $secretProvider; |
44
|
4 |
|
$this->unauthenticatedHandler = $unauthenticatedHandler; |
45
|
4 |
|
$this->hmacVerifier = new Verifier(); |
46
|
4 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* {@inheritdoc} |
50
|
|
|
*/ |
51
|
4 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
52
|
|
|
{ |
53
|
4 |
|
if (null === $key = $this->keyProvider->getKeyFrom($request)) { |
54
|
1 |
|
return $this->unauthenticatedHandler->handle( |
55
|
1 |
|
$request->withAttribute(Specification::HMAC_ERROR, Specification::ERR_NO_KEY) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
3 |
|
if (null === $secret = $this->secretProvider->getSecretFor($key)) { |
60
|
1 |
|
return $this->unauthenticatedHandler->handle( |
61
|
1 |
|
$request->withAttribute(Specification::HMAC_ERROR, Specification::ERR_NO_SECRET) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
if (false === $this->hmacVerifier->verify($request, $secret)) { |
66
|
1 |
|
return $this->unauthenticatedHandler->handle( |
67
|
1 |
|
$request->withAttribute(Specification::HMAC_ERROR, Specification::ERR_BROKEN_SIG) |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
return $handler->handle($request); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|