3 namespace BookStack\Auth\Access\Oidc;
23 * @var array[]|string[]
35 protected $tokenParts = [];
37 public function __construct(string $token, string $issuer, array $keys)
40 $this->issuer = $issuer;
45 * Parse the token content into its components.
47 protected function parse(string $token): void
49 $this->tokenParts = explode('.', $token);
50 $this->header = $this->parseEncodedTokenPart($this->tokenParts[0]);
51 $this->payload = $this->parseEncodedTokenPart($this->tokenParts[1] ?? '');
52 $this->signature = $this->base64UrlDecode($this->tokenParts[2] ?? '') ?: '';
56 * Parse a Base64-JSON encoded token part.
57 * Returns the data as a key-value array or empty array upon error.
59 protected function parseEncodedTokenPart(string $part): array
61 $json = $this->base64UrlDecode($part) ?: '{}';
62 $decoded = json_decode($json, true);
64 return is_array($decoded) ? $decoded : [];
68 * Base64URL decode. Needs some character conversions to be compatible
69 * with PHP's default base64 handling.
71 protected function base64UrlDecode(string $encoded): string
73 return base64_decode(strtr($encoded, '-_', '+/'));
77 * Validate all possible parts of the id token.
79 * @throws OidcInvalidTokenException
81 public function validate(string $clientId): bool
83 $this->validateTokenStructure();
84 $this->validateTokenSignature();
85 $this->validateTokenClaims($clientId);
91 * Fetch a specific claim from this token.
92 * Returns null if it is null or does not exist.
96 public function getClaim(string $claim)
98 return $this->payload[$claim] ?? null;
102 * Get all returned claims within the token.
104 public function getAllClaims(): array
106 return $this->payload;
110 * Validate the structure of the given token and ensure we have the required pieces.
111 * As per https://datatracker.ietf.org/doc/html/rfc7519#section-7.2.
113 * @throws OidcInvalidTokenException
115 protected function validateTokenStructure(): void
117 foreach (['header', 'payload'] as $prop) {
118 if (empty($this->$prop) || !is_array($this->$prop)) {
119 throw new OidcInvalidTokenException("Could not parse out a valid {$prop} within the provided token");
123 if (empty($this->signature) || !is_string($this->signature)) {
124 throw new OidcInvalidTokenException('Could not parse out a valid signature within the provided token');
129 * Validate the signature of the given token and ensure it validates against the provided key.
131 * @throws OidcInvalidTokenException
133 protected function validateTokenSignature(): void
135 if ($this->header['alg'] !== 'RS256') {
136 throw new OidcInvalidTokenException("Only RS256 signature validation is supported. Token reports using {$this->header['alg']}");
139 $parsedKeys = array_map(function ($key) {
141 return new OidcJwtSigningKey($key);
142 } catch (OidcInvalidKeyException $e) {
143 throw new OidcInvalidTokenException('Failed to read signing key with error: ' . $e->getMessage());
147 $parsedKeys = array_filter($parsedKeys);
149 $contentToSign = $this->tokenParts[0] . '.' . $this->tokenParts[1];
150 /** @var OidcJwtSigningKey $parsedKey */
151 foreach ($parsedKeys as $parsedKey) {
152 if ($parsedKey->verify($contentToSign, $this->signature)) {
157 throw new OidcInvalidTokenException('Token signature could not be validated using the provided keys');
161 * Validate the claims of the token.
162 * As per https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
164 * @throws OidcInvalidTokenException
166 protected function validateTokenClaims(string $clientId): void
168 // 1. The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery)
169 // MUST exactly match the value of the iss (issuer) Claim.
170 if (empty($this->payload['iss']) || $this->issuer !== $this->payload['iss']) {
171 throw new OidcInvalidTokenException('Missing or non-matching token issuer value');
174 // 2. The Client MUST validate that the aud (audience) Claim contains its client_id value registered
175 // at the Issuer identified by the iss (issuer) Claim as an audience. The ID Token MUST be rejected
176 // if the ID Token does not list the Client as a valid audience, or if it contains additional
177 // audiences not trusted by the Client.
178 if (empty($this->payload['aud'])) {
179 throw new OidcInvalidTokenException('Missing token audience value');
182 $aud = is_string($this->payload['aud']) ? [$this->payload['aud']] : $this->payload['aud'];
183 if (count($aud) !== 1) {
184 throw new OidcInvalidTokenException('Token audience value has ' . count($aud) . ' values, Expected 1');
187 if ($aud[0] !== $clientId) {
188 throw new OidcInvalidTokenException('Token audience value did not match the expected client_id');
191 // 3. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp Claim is present.
192 // NOTE: Addressed by enforcing a count of 1 above.
194 // 4. If an azp (authorized party) Claim is present, the Client SHOULD verify that its client_id
195 // is the Claim Value.
196 if (isset($this->payload['azp']) && $this->payload['azp'] !== $clientId) {
197 throw new OidcInvalidTokenException('Token authorized party exists but does not match the expected client_id');
200 // 5. The current time MUST be before the time represented by the exp Claim
201 // (possibly allowing for some small leeway to account for clock skew).
202 if (empty($this->payload['exp'])) {
203 throw new OidcInvalidTokenException('Missing token expiration time value');
208 if ($now >= (intval($this->payload['exp']) + $skewSeconds)) {
209 throw new OidcInvalidTokenException('Token has expired');
212 // 6. The iat Claim can be used to reject tokens that were issued too far away from the current time,
213 // limiting the amount of time that nonces need to be stored to prevent attacks.
214 // The acceptable range is Client specific.
215 if (empty($this->payload['iat'])) {
216 throw new OidcInvalidTokenException('Missing token issued at time value');
219 $dayAgo = time() - 86400;
220 $iat = intval($this->payload['iat']);
221 if ($iat > ($now + $skewSeconds) || $iat < $dayAgo) {
222 throw new OidcInvalidTokenException('Token issue at time is not recent or is invalid');
225 // 7. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value is appropriate.
226 // The meaning and processing of acr Claim Values is out of scope for this document.
227 // NOTE: Not used for our case here. acr is not requested.
229 // 8. When a max_age request is made, the Client SHOULD check the auth_time Claim value and request
230 // re-authentication if it determines too much time has elapsed since the last End-User authentication.
231 // NOTE: Not used for our case here. A max_age request is not made.
233 // Custom: Ensure the "sub" (Subject) Claim exists and has a value.
234 if (empty($this->payload['sub'])) {
235 throw new OidcInvalidTokenException('Missing token subject value');