1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* This file is part of the daikon-cqrs/security-interop project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Daikon\Security\Middleware; |
10
|
|
|
|
11
|
|
|
use Daikon\Config\ConfigProviderInterface; |
12
|
|
|
use Firebase\JWT\JWT; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
15
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
16
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
17
|
|
|
use UnexpectedValueException; |
18
|
|
|
|
19
|
|
|
final class JwtDecoder implements MiddlewareInterface |
20
|
|
|
{ |
21
|
|
|
public const DEFAULT_ATTR_JWT = '__Host-_jwt'; |
22
|
|
|
public const DEFAULT_ATTR_XSRF = '__Host-_xsrf'; |
23
|
|
|
public const DEFAULT_HEADER_XSRF = 'X-XSRF-TOKEN'; |
24
|
|
|
|
25
|
|
|
private ConfigProviderInterface $config; |
26
|
|
|
|
27
|
3 |
|
public function __construct(ConfigProviderInterface $config) |
28
|
|
|
{ |
29
|
3 |
|
$this->config = $config; |
30
|
3 |
|
} |
31
|
|
|
|
32
|
3 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
33
|
|
|
{ |
34
|
3 |
|
$authConfig = $this->config->get('project.authentication', []); |
35
|
3 |
|
$jwtAttribute = $authConfig['jwt']['attribute'] ?? self::DEFAULT_ATTR_JWT; |
36
|
3 |
|
$xsrfAttribute = $authConfig['xsrf']['attribute'] ?? self::DEFAULT_ATTR_XSRF; |
37
|
3 |
|
$xsrfHeader = $authConfig['xsrf']['header'] ?? self::DEFAULT_HEADER_XSRF; |
38
|
|
|
|
39
|
3 |
|
$cookieParams = $request->getCookieParams(); |
40
|
3 |
|
$encodedJwt = $cookieParams[$jwtAttribute] ?? $this->parseAuthHeader($request->getHeaderLine('Authorization')); |
41
|
3 |
|
$xsrfToken = $cookieParams[$xsrfAttribute] ?? $request->getHeaderLine($xsrfHeader); |
42
|
|
|
|
43
|
3 |
|
$decodedJwt = null; |
44
|
3 |
|
if ($encodedJwt) { |
45
|
2 |
|
$decodedJwt = $this->decodeJwt($encodedJwt); |
46
|
|
|
} |
47
|
|
|
|
48
|
3 |
|
return $handler->handle( |
49
|
3 |
|
$request->withAttribute($jwtAttribute, $decodedJwt)->withAttribute($xsrfAttribute, $xsrfToken) |
50
|
|
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
private function decodeJwt(string $jwt): ?object |
54
|
|
|
{ |
55
|
2 |
|
$secretKey = $this->config->get('project.authentication.jwt.secret', 'daikon'); |
56
|
|
|
try { |
57
|
2 |
|
return JWT::decode($jwt, $secretKey, ['HS256']); |
58
|
1 |
|
} catch (UnexpectedValueException $error) { |
59
|
1 |
|
return null; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
3 |
|
private function parseAuthHeader(string $header): ?string |
64
|
|
|
{ |
65
|
3 |
|
return preg_match('/^Bearer\s+(?<token>[a-z0-9\._-]+)$/i', $header, $matches) |
66
|
2 |
|
? $matches['token'] |
67
|
3 |
|
: null; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|