|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thruster\Component\HttpMiddlewares; |
|
4
|
|
|
|
|
5
|
|
|
use Namshi\JOSE\SimpleJWS; |
|
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
8
|
|
|
use Thruster\Component\HttpMessage\Response; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class JWTValidatorMiddleware |
|
12
|
|
|
* |
|
13
|
|
|
* @package Thruster\Component\HttpMiddlewares |
|
14
|
|
|
* @author Aurimas Niekis <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
class JWTValidatorMiddleware |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var resource |
|
20
|
|
|
*/ |
|
21
|
|
|
private $publicKey; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var string |
|
25
|
|
|
*/ |
|
26
|
|
|
private $encoder; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @var ResponseInterface |
|
30
|
|
|
*/ |
|
31
|
|
|
private $invalidResponse; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @var bool |
|
35
|
|
|
*/ |
|
36
|
|
|
private $allRequests; |
|
37
|
|
|
|
|
38
|
5 |
|
public function __construct( |
|
39
|
|
|
$publicKey, |
|
40
|
|
|
string $encoder = 'RS256', |
|
41
|
|
|
bool $allRequests = false, |
|
42
|
|
|
ResponseInterface $invalidResponse = null |
|
43
|
|
|
) { |
|
44
|
5 |
|
$this->publicKey = $publicKey; |
|
45
|
5 |
|
$this->encoder = $encoder; |
|
46
|
5 |
|
$this->allRequests = $allRequests; |
|
47
|
|
|
|
|
48
|
5 |
|
if (null !== $invalidResponse) { |
|
49
|
3 |
|
$this->invalidResponse = $invalidResponse; |
|
50
|
|
|
} else { |
|
51
|
2 |
|
$this->invalidResponse = new Response(403); |
|
52
|
|
|
} |
|
53
|
5 |
|
} |
|
54
|
|
|
|
|
55
|
5 |
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
|
56
|
|
|
{ |
|
57
|
5 |
|
if (false === $request->hasHeader('Authorization')) { |
|
58
|
2 |
|
if (false === $this->allRequests) { |
|
59
|
1 |
|
return $next($request, $response); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
1 |
|
return $this->invalidResponse; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
3 |
|
$token = $request->getHeaderLine('Authorization'); |
|
66
|
3 |
|
if (false === strpos($token, 'Bearer ')) { |
|
67
|
1 |
|
return $this->invalidResponse; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
2 |
|
$token = substr($token, 7); |
|
71
|
|
|
|
|
72
|
|
|
/** @var SimpleJWS $jws */ |
|
73
|
2 |
|
$jws = SimpleJWS::load($token, false); |
|
74
|
|
|
|
|
75
|
2 |
|
if (false === $jws->isValid($this->publicKey, $this->encoder)) { |
|
76
|
1 |
|
return $this->invalidResponse; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
1 |
|
return $next($request->withAttribute('jwt', $jws->getPayload()), $response); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|