]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcUserinfoResponse.php
bb6c2454ad23a91f39b11b8dfa127940c31c3d0e
[bookstack] / app / Access / Oidc / OidcUserinfoResponse.php
1 <?php
2
3 namespace BookStack\Access\Oidc;
4
5 use Psr\Http\Message\ResponseInterface;
6
7 class OidcUserinfoResponse implements ProvidesClaims
8 {
9     protected array $claims = [];
10     protected ?OidcJwtWithClaims $jwt = null;
11
12     public function __construct(ResponseInterface $response, string $issuer, array $keys)
13     {
14         $contentType = $response->getHeader('Content-Type')[0];
15         if ($contentType === 'application/json') {
16             $this->claims = json_decode($response->getBody()->getContents(), true);
17         }
18
19         if ($contentType === 'application/jwt') {
20             $this->jwt = new OidcJwtWithClaims($response->getBody()->getContents(), $issuer, $keys);
21             $this->claims = $this->jwt->getAllClaims();
22         }
23
24         // TODO - Response validation (5.3.4):
25             // TODO - Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125].
26             // TODO - If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration.
27             // TODO - If the response was signed, the Client SHOULD validate the signature according to JWS [JWS].
28     }
29
30     /**
31      * @throws OidcInvalidTokenException
32      */
33     public function validate(string $idTokenSub): bool
34     {
35         if (!is_null($this->jwt)) {
36             $this->jwt->validateCommonClaims();
37         }
38
39         $sub = $this->getClaim('sub');
40
41         // Spec: v1.0 5.3.2: The sub (subject) Claim MUST always be returned in the UserInfo Response.
42         if (!is_string($sub) || empty($sub)) {
43             throw new OidcInvalidTokenException("No valid subject value found in userinfo data");
44         }
45
46         // Spec: v1.0 5.3.2: The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token;
47         // if they do not match, the UserInfo Response values MUST NOT be used.
48         if ($idTokenSub !== $sub) {
49             throw new OidcInvalidTokenException("Subject value provided in the userinfo endpoint does not match the provided ID token value");
50         }
51
52         return true;
53     }
54
55     public function getClaim(string $claim): mixed
56     {
57         return $this->claims[$claim] ?? null;
58     }
59
60     public function getAllClaims(): array
61     {
62         return $this->claims;
63     }
64 }