provider->setting('issuer'), '/'); } public function clientId(): string { return (string) $this->provider->setting('client_id'); } /** * Discovery-Dokument (1 Stunde zwischengespeichert). * * @return array */ public function discovery(bool $refresh = false): array { $key = 'oidc.discovery.'.$this->provider->id.'.'.md5($this->issuer()); if ($refresh) { Cache::forget($key); } return Cache::remember($key, 3600, function () { $response = $this->http()->get($this->issuer().'/.well-known/openid-configuration'); if (! $response->successful() || ! is_array($response->json())) { throw new IdentityException('Der Anmeldedienst ist nicht erreichbar (Discovery: HTTP '.$response->status().').'); } $document = (array) $response->json(); foreach (['issuer', 'authorization_endpoint', 'token_endpoint', 'jwks_uri'] as $field) { if (! is_string($document[$field] ?? null) || $document[$field] === '') { throw new IdentityException("Das Discovery-Dokument des Anmeldedienstes enthält kein „{$field}“."); } } // Der Aussteller muss exakt der konfigurierten Adresse entsprechen (OIDC Discovery 4.3). if (rtrim($document['issuer'], '/') !== $this->issuer()) { throw new IdentityException('Der Anmeldedienst meldet einen anderen Aussteller ('.$document['issuer'].') als eingetragen.'); } return $document; }); } /** * @param array{state: string, nonce: string, code_challenge: string} $security */ public function authorizationUrl(string $redirectUri, array $security): string { $endpoint = (string) $this->discovery()['authorization_endpoint']; $params = array_filter([ 'client_id' => $this->clientId(), 'response_type' => 'code', 'redirect_uri' => $redirectUri, 'scope' => $this->scopes(), 'state' => $security['state'], 'nonce' => $security['nonce'], 'code_challenge' => $security['code_challenge'], 'code_challenge_method' => 'S256', 'prompt' => $this->provider->setting('prompt') ?: null, ]); return $endpoint.(str_contains($endpoint, '?') ? '&' : '?').http_build_query($params); } public function scopes(): string { $scopes = preg_split('/[\s,]+/', (string) $this->provider->setting('scopes', 'openid profile email'), -1, PREG_SPLIT_NO_EMPTY) ?: []; return implode(' ', array_unique(['openid', ...$scopes])); } /** * @return array{id_token: string, access_token: ?string} */ public function exchangeCode(string $code, string $redirectUri, string $verifier): array { $params = [ 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $redirectUri, 'code_verifier' => $verifier, ]; $secret = (string) $this->provider->setting('client_secret'); $request = $this->http()->asForm(); if ($this->provider->setting('token_auth', 'client_secret_basic') === 'client_secret_post') { $params += ['client_id' => $this->clientId(), 'client_secret' => $secret]; } else { $request = $request->withBasicAuth(rawurlencode($this->clientId()), rawurlencode($secret)); } $response = $request->post((string) $this->discovery()['token_endpoint'], $params); if (! $response->successful()) { logger()->warning('OIDC-Tokenabruf fehlgeschlagen: HTTP '.$response->status().' '.mb_substr($response->body(), 0, 300)); throw new IdentityException($response->json('error') === 'invalid_client' ? 'Der Anmeldedienst hat die Zugangsdaten des Portals abgelehnt. Bitte wenden Sie sich an die Administration.' : 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte erneut versuchen.'); } if (! is_string($response->json('id_token'))) { throw new IdentityException('Der Anmeldedienst hat kein ID-Token geliefert.'); } return ['id_token' => $response->json('id_token'), 'access_token' => is_string($response->json('access_token')) ? $response->json('access_token') : null]; } /** * Signatur, Aussteller, Empfänger, Gültigkeit und Nonce prüfen. * * @return array */ public function validateIdToken(string $token, string $nonce): array { JWT::$leeway = 120; try { $claims = $this->decode($token, $this->jwks()); } catch (UnexpectedValueException $e) { if (! str_contains($e->getMessage(), '"kid"')) { throw new IdentityException('Die Anmeldung konnte nicht bestätigt werden.', previous: $e); } // Schlüsselwechsel beim Anbieter: einmal neu laden. try { $claims = $this->decode($token, $this->jwks(refresh: true)); } catch (UnexpectedValueException $e) { throw new IdentityException('Die Anmeldung konnte nicht bestätigt werden.', previous: $e); } } if (rtrim((string) ($claims['iss'] ?? ''), '/') !== rtrim((string) $this->discovery()['issuer'], '/')) { throw new IdentityException('Die Anmeldung stammt nicht vom erwarteten Anmeldedienst.'); } $audiences = (array) ($claims['aud'] ?? []); if (! in_array($this->clientId(), $audiences, true) || (count($audiences) > 1 && ($claims['azp'] ?? null) !== $this->clientId())) { throw new IdentityException('Die Anmeldung war für eine andere Anwendung bestimmt.'); } if (! hash_equals($nonce, (string) ($claims['nonce'] ?? ''))) { throw new IdentityException('Die Anmeldung konnte nicht zugeordnet werden. Bitte erneut versuchen.'); } return $claims; } /** * @return array */ public function userinfo(string $accessToken): array { $endpoint = $this->discovery()['userinfo_endpoint'] ?? null; if (! is_string($endpoint) || $endpoint === '') { return []; } $response = $this->http()->withToken($accessToken)->acceptJson()->get($endpoint); return $response->successful() && is_array($response->json()) ? (array) $response->json() : []; } /** * @return array{keys: list>} */ public function jwks(bool $refresh = false): array { $key = 'oidc.jwks.'.$this->provider->id; if ($refresh) { Cache::forget($key); } return Cache::remember($key, 3600, function () { $response = $this->http()->get((string) $this->discovery()['jwks_uri']); if (! $response->successful() || ! is_array($response->json('keys'))) { throw new IdentityException('Die Schlüssel des Anmeldedienstes sind nicht abrufbar.'); } return ['keys' => array_values((array) $response->json('keys'))]; }); } /** * @param array{keys: list>} $jwks * @return array */ private function decode(string $token, array $jwks): array { try { // Nur Signaturschlüssel; Schlüssel ohne „alg“ gelten als RS256. $keys = ['keys' => array_values(array_filter($jwks['keys'], fn ($k) => ($k['use'] ?? 'sig') === 'sig'))]; return (array) json_decode(json_encode(JWT::decode($token, JWK::parseKeySet($keys, 'RS256'))), true); } catch (UnexpectedValueException $e) { throw $e; } catch (Throwable $e) { throw new IdentityException('Die Anmeldung konnte nicht bestätigt werden.', previous: $e); } } private function http(): PendingRequest { return Http::timeout(15)->connectTimeout(5)->acceptJson(); } }