Loheide-eu-mitarbeiterplatt.../plugins-core/oidc/src/OidcClient.php
Friederich Loheide 4fcc41ed30
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m41s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m48s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m15s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 3m17s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m48s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m41s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m26s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m59s
Phase 6 (Teil 2): OpenID Connect, LDAP/AD und SAML 2
- Gemeinsamer Treiber-Unterbau (App\Identity\IdentityDriver, IdentityDrivers,
  IdentityLogin, AttributeProfile); Entra ID nutzt ihn ebenfalls
- Plugins oidc, ldap und saml mit Profil- und Gruppen-Zuordnung
- Admin: Verfahren wählen, Formular je Verfahren, zuletzt empfangene Angaben
- onelogin/php-saml als neue Abhängigkeit

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 12:38:32 +00:00

236 lines
8.6 KiB
PHP

<?php
namespace Inhaus\Plugins\Oidc;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
use UnexpectedValueException;
/**
* OpenID Connect nach Standard: Discovery, Autorisierungscode mit PKCE,
* Prüfung des ID-Tokens über die Schlüssel des Anbieters, UserInfo.
*/
class OidcClient
{
public function __construct(private readonly IdentityProvider $provider) {}
public function issuer(): string
{
return rtrim((string) $this->provider->setting('issuer'), '/');
}
public function clientId(): string
{
return (string) $this->provider->setting('client_id');
}
/**
* Discovery-Dokument (1 Stunde zwischengespeichert).
*
* @return array<string, mixed>
*/
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<string, mixed>
*/
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<string, mixed>
*/
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<array<string, mixed>>}
*/
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<array<string, mixed>>} $jwks
* @return array<string, mixed>
*/
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();
}
}