Debian Codegraph @

lib/3rdParty/composer/facile-it/php-openid-client/src/Service/UserInfoService.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Facile\OpenIDClient\Service;
6
7 use Facile\OpenIDClient\Client\ClientInterface as OpenIDClient;
8 use Facile\OpenIDClient\Exception\InvalidArgumentException;
9 use Facile\OpenIDClient\Exception\OAuth2Exception;
10 use Facile\OpenIDClient\Exception\RuntimeException;
11 use Facile\OpenIDClient\Token\TokenSetInterface;
12 use Facile\OpenIDClient\Token\TokenVerifierBuilderInterface;
13 use JsonException;
14 use Psr\Http\Client\ClientExceptionInterface;
15 use Psr\Http\Client\ClientInterface;
16 use Psr\Http\Message\RequestFactoryInterface;
17
18 use function http_build_query;
19 use function json_decode;
20 use function sprintf;
21
22 /**
23 * @psalm-import-type TokenSetClaimsType from TokenSetInterface
24 */
25 final class UserInfoService
26 {
27 private ClientInterface $client;
28
29 private RequestFactoryInterface $requestFactory;
30
31 private TokenVerifierBuilderInterface $userInfoVerifierBuilder;
32
33 public function __construct(
34 TokenVerifierBuilderInterface $userInfoVerifierBuilder,
35 ClientInterface $client,
36 RequestFactoryInterface $requestFactory
37 ) {
38 $this->userInfoVerifierBuilder = $userInfoVerifierBuilder;
39 $this->client = $client;
40 $this->requestFactory = $requestFactory;
41 }
42
43 /**
44 * @return array<string, mixed>
45 */
46 public function getUserInfo(OpenIDClient $client, TokenSetInterface $tokenSet, bool $useBody = false): array
47 {
48 $accessToken = $tokenSet->getAccessToken();
49
50 if (null === $accessToken) {
51 throw new RuntimeException('Unable to get an access token from the token set');
52 }
53
54 $clientMetadata = $client->getMetadata();
55 $issuerMetadata = $client->getIssuer()->getMetadata();
56
57 $mTLS = true === $clientMetadata->get('tls_client_certificate_bound_access_tokens');
58
59 $endpointUri = $issuerMetadata->getUserinfoEndpoint();
60
61 if ($mTLS) {
62 $endpointUri = $issuerMetadata->getMtlsEndpointAliases()['userinfo_endpoint'] ?? $endpointUri;
63 }
64
65 if (null === $endpointUri) {
66 throw new InvalidArgumentException('Invalid issuer userinfo endpoint');
67 }
68
69 $expectJwt = null !== $clientMetadata->getUserinfoSignedResponseAlg()
70 || null !== $clientMetadata->getUserinfoEncryptedResponseAlg()
71 || null !== $clientMetadata->getUserinfoEncryptedResponseEnc();
72
73 if ($useBody) {
74 $request = $this->requestFactory->createRequest('POST', $endpointUri)
75 ->withHeader('accept', $expectJwt ? 'application/jwt' : 'application/json')
76 ->withHeader('content-type', 'application/x-www-form-urlencoded');
77 $request->getBody()->write(http_build_query(['access_token' => $accessToken]));
78 } else {
79 $request = $this->requestFactory->createRequest('GET', $endpointUri)
80 ->withHeader('accept', $expectJwt ? 'application/jwt' : 'application/json')
81 ->withHeader('authorization', ($tokenSet->getTokenType() ?? 'Bearer') . ' ' . $accessToken);
82 }
83
84 $httpClient = $client->getHttpClient() ?? $this->client;
85
86 try {
87 $response = $httpClient->sendRequest($request);
88 } catch (ClientExceptionInterface $e) {
89 throw new RuntimeException('Unable to get userinfo', 0, $e);
90 }
91
92 if (200 !== $response->getStatusCode()) {
93 throw OAuth2Exception::fromResponse($response);
94 }
95
96 if ($expectJwt) {
97 /** @var TokenSetClaimsType $payload */
98 $payload = $this->userInfoVerifierBuilder->build($client)
99 ->verify((string) $response->getBody());
100 } else {
101 try {
102 /** @var TokenSetClaimsType $payload */
103 $payload = json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
104 } catch (JsonException $e) {
105 throw new RuntimeException('Unable to parse userinfo claims', 0, $e);
106 }
107 }
108
109 $idToken = $tokenSet->getIdToken();
110
111 if (null === $idToken) {
112 return $payload;
113 }
114
115 // check expected sub
116 $expectedSub = $tokenSet->claims()['sub'] ?? null;
117
118 if (null === $expectedSub) {
119 throw new RuntimeException('Unable to get sub claim from id_token');
120 }
121
122 if ($expectedSub !== ($payload['sub'] ?? null)) {
123 throw new RuntimeException(
124 sprintf('Userinfo sub mismatch, expected %s, got: %s', $expectedSub, $payload['sub'] ?? '')
125 );
126 }
127
128 return $payload;
129 }
130 }