3 namespace BookStack\Auth\Access\Oidc;
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 all possible parts of the id token.
60 * @throws OidcInvalidTokenException
62 public function validate(string $clientId): bool
64 $this->validateTokenStructure();
65 $this->validateTokenSignature();
66 $this->validateTokenClaims($clientId);
72 * Fetch a specific claim from this token.
73 * Returns null if it is null or does not exist.
77 public function getClaim(string $claim)
79 return $this->payload[$claim] ?? null;
83 * Get all returned claims within the token.
85 public function getAllClaims(): array
87 return $this->payload;
91 * Replace the existing claim data of this token with that provided.
93 public function replaceClaims(array $claims): void
95 $this->payload = $claims;
99 * Validate the structure of the given token and ensure we have the required pieces.
100 * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
102 * @throws OidcInvalidTokenException
104 protected function validateTokenStructure(): void
106 foreach (['header', 'payload'] as $prop) {
107 if (empty($this->$prop) || !is_array($this->$prop)) {
108 throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
112 if (empty($this->signature) || !is_string($this->signature)) {
113 throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
118 * Validate the signature of the given token and ensure it validates against the provided key.
120 * @throws OidcInvalidTokenException
122 protected function validateTokenSignature(): void
124 if ($this->header['alg'] !== 'RS256') {
125 throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
128 $parsedKeys = array_map(function ($key) {
130 return new OidcJwtSigningKey($key);
131 } catch (OidcInvalidKeyException $e) {
132 throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
136 $parsedKeys = array_filter($parsedKeys);
138 $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
139 /** @var OidcJwtSigningKey $parsedKey */
140 foreach ($parsedKeys as $parsedKey) {
141 if ($parsedKey->verify($contentToSign, $this->signature)) {
146 throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
150 * Validate the claims of the token.
151 * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
153 * @throws OidcInvalidTokenException
155 protected function validateTokenClaims(string $clientId): void
157 // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
158 // MUST exactly match the value of the iss (issuer) Claim.
159 if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
160 throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
163 // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
164 // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
165 // if the ID Token does not list the Client as a valid audience, or if it contains additional
166 // audiences not trusted by the Client.
167 if (empty($this->payload['aud'])) {
168 throw new OidcInvalidTokenException('Missing token audience value');
171 $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
172 if (count($aud) !== 1) {
173 throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1');
176 if ($aud[0] !== $clientId) {
177 throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');
180 // 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
181 // NOTE: Addressed by enforcing a count of 1 above.
183 // 4. If an azp (authorized party) Claim is present, the Client SHOULD verify that its client_id
184 // is the Claim Value.
185 if (isset($this->payload['azp']) && $this->payload['azp'] !== $clientId) {
186 throw new OidcInvalidTokenException('Token authorized party exists but does not match the expected client_id');
189 // 5. The current time MUST be before the time represented by the exp Claim
190 // (possibly allowing for some small leeway to account for clock skew).
191 if (empty($this->payload['exp'])) {
192 throw new OidcInvalidTokenException('Missing token expiration time value');
197 if ($now >= (intval($this->payload['exp']) + $skewSeconds)) {
198 throw new OidcInvalidTokenException('Token has expired');
201 // 6. The iat Claim can be used to reject tokens that were issued too far away from the current time,
202 // limiting the amount of time that nonces need to be stored to prevent attacks.
203 // The acceptable range is Client specific.
204 if (empty($this->payload['iat'])) {
205 throw new OidcInvalidTokenException('Missing token issued at time value');
208 $dayAgo = time() - 86400;
209 $iat = intval($this->payload['iat']);
210 if ($iat > ($now + $skewSeconds) || $iat < $dayAgo) {
211 throw new OidcInvalidTokenException('Token issue at time is not recent or is invalid');
214 // 7. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value is appropriate.
215 // The meaning and processing of acr Claim Values is out of scope for this document.
216 // NOTE: Not used for our case here. acr is not requested.
218 // 8. When a max_age request is made, the Client SHOULD check the auth_time Claim value and request
219 // re-authentication if it determines too much time has elapsed since the last End-User authentication.
220 // NOTE: Not used for our case here. A max_age request is not made.
222 // Custom: Ensure the "sub" (Subject) Claim exists and has a value.
223 if (empty($this->payload['sub'])) {
224 throw new OidcInvalidTokenException('Missing token subject value');