3 namespace BookStack\Access\Oidc;
5 class OidcJwtWithClaims implements ProvidesClaims
7 protected array $header;
8 protected array $payload;
9 protected string $signature;
10 protected string $issuer;
11 protected array $tokenParts = [];
14 * @var array[]|string[]
16 protected array $keys;
18 public function __construct(string $token, string $issuer, array $keys)
21 $this->issuer = $issuer;
26 * Parse the token content into its components.
28 protected function parse(string $token): void
30 $this->tokenParts = explode('.', $token);
31 $this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
32 $this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
33 $this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
37 * Parse a Base64-JSON encoded token part.
38 * Returns the data as a key-value array or empty array upon error.
40 protected function parseEncodedTokenPart(string $part): array
42 $json = $this->base64UrlDecode($part) ?: '{}';
43 $decoded = json_decode($json, true);
45 return is_array($decoded) ? $decoded : [];
49 * Base64URL decode. Needs some character conversions to be compatible
50 * with PHP's default base64 handling.
52 protected function base64UrlDecode(string $encoded): string
54 return base64_decode(strtr($encoded, '-_', '+/'));
58 * Validate common parts of OIDC JWT tokens.
60 * @throws OidcInvalidTokenException
62 public function validateCommonTokenDetails(string $clientId): bool
64 $this->validateTokenStructure();
65 $this->validateTokenSignature();
66 $this->validateCommonClaims($clientId);
72 * Fetch a specific claim from this token.
73 * Returns null if it is null or does not exist.
75 public function getClaim(string $claim): mixed
77 return $this->payload[$claim] ?? null;
81 * Get all returned claims within the token.
83 public function getAllClaims(): array
85 return $this->payload;
89 * Replace the existing claim data of this token with that provided.
91 public function replaceClaims(array $claims): void
93 $this->payload = $claims;
97 * Validate the structure of the given token and ensure we have the required pieces.
98 * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
100 * @throws OidcInvalidTokenException
102 protected function validateTokenStructure(): void
104 foreach (['header', 'payload'] as $prop) {
105 if (empty($this->$prop) || !is_array($this->$prop)) {
106 throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
110 if (empty($this->signature) || !is_string($this->signature)) {
111 throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
116 * Validate the signature of the given token and ensure it validates against the provided key.
118 * @throws OidcInvalidTokenException
120 protected function validateTokenSignature(): void
122 if ($this->header['alg'] !== 'RS256') {
123 throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
126 $parsedKeys = array_map(function ($key) {
128 return new OidcJwtSigningKey($key);
129 } catch (OidcInvalidKeyException $e) {
130 throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
134 $parsedKeys = array_filter($parsedKeys);
136 $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
137 /** @var OidcJwtSigningKey $parsedKey */
138 foreach ($parsedKeys as $parsedKey) {
139 if ($parsedKey->verify($contentToSign, $this->signature)) {
144 throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
148 * Validate common claims for OIDC JWT tokens.
149 * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
150 * and https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
152 * @throws OidcInvalidTokenException
154 protected function validateCommonClaims(string $clientId): void
156 // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
157 // MUST exactly match the value of the iss (issuer) Claim.
158 if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
159 throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
162 // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
163 // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
164 // if the ID Token does not list the Client as a valid audience.
165 if (empty($this->payload['aud'])) {
166 throw new OidcInvalidTokenException('Missing token audience value');
169 $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
170 if (!in_array($clientId, $aud, true)) {
171 throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');