1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace TMV\OpenIdClient\Middleware; |
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 TMV\OpenIdClient\Client\ClientInterface; |
12
|
|
|
use TMV\OpenIdClient\Exception\LogicException; |
13
|
|
|
use TMV\OpenIdClient\Exception\RuntimeException; |
14
|
|
|
use TMV\OpenIdClient\Service\UserinfoService; |
15
|
|
|
use TMV\OpenIdClient\Token\TokenSetInterface; |
16
|
|
|
|
17
|
|
|
class UserInfoMiddleware implements MiddlewareInterface |
18
|
|
|
{ |
19
|
|
|
public const USERINFO_ATTRIBUTE = self::class; |
20
|
|
|
|
21
|
|
|
/** @var UserinfoService */ |
22
|
|
|
private $userinfoService; |
23
|
|
|
|
24
|
|
|
/** @var null|ClientInterface */ |
25
|
|
|
private $client; |
26
|
|
|
|
27
|
|
|
public function __construct( |
28
|
|
|
UserinfoService $userinfoService, |
29
|
|
|
?ClientInterface $client = null |
30
|
|
|
) { |
31
|
|
|
$this->userinfoService = $userinfoService; |
32
|
|
|
$this->client = $client; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
36
|
|
|
{ |
37
|
|
|
$tokenSet = $request->getAttribute(TokenSetInterface::class); |
38
|
|
|
$client = $this->client ?: $request->getAttribute(ClientInterface::class); |
39
|
|
|
|
40
|
|
|
if (! $client instanceof ClientInterface) { |
41
|
|
|
throw new LogicException('No OpenID client provided'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (! $tokenSet instanceof TokenSetInterface) { |
45
|
|
|
throw new RuntimeException('Unable to get token response attribute'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$claims = $this->userinfoService->getUserInfo($client, $tokenSet); |
49
|
|
|
|
50
|
|
|
return $handler->handle($request->withAttribute(self::USERINFO_ATTRIBUTE, $claims)); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|