|
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
|
4 |
|
public function __construct($publicKey, string $encoder = 'RS256', ResponseInterface $invalidResponse = null) |
|
34
|
|
|
{ |
|
35
|
4 |
|
$this->publicKey = $publicKey; |
|
36
|
4 |
|
$this->encoder = $encoder; |
|
37
|
|
|
|
|
38
|
4 |
|
if (null !== $invalidResponse) { |
|
39
|
2 |
|
$this->invalidResponse = $invalidResponse; |
|
40
|
|
|
} else { |
|
41
|
2 |
|
$this->invalidResponse = new Response(403); |
|
42
|
|
|
} |
|
43
|
4 |
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
|
46
|
|
|
{ |
|
47
|
4 |
|
if (false === $request->hasHeader('Authorization')) { |
|
48
|
1 |
|
return $next($request, $response); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
3 |
|
$token = $request->getHeaderLine('Authorization'); |
|
52
|
3 |
|
if (false === strpos($token, 'Bearer ')) { |
|
53
|
1 |
|
return $this->invalidResponse; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
$token = substr($token, 7); |
|
57
|
|
|
|
|
58
|
|
|
/** @var SimpleJWS $jws */ |
|
59
|
2 |
|
$jws = SimpleJWS::load($token, false); |
|
60
|
|
|
|
|
61
|
2 |
|
if (false === $jws->isValid($this->publicKey, $this->encoder)) { |
|
62
|
1 |
|
return $this->invalidResponse; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
return $next($request->withAttribute('jwt', $jws->getPayload()), $response); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|