Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m50s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 7m34s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 5m45s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 5m30s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 7m7s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 7m9s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 6m8s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 6m5s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 48s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m5s
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
248 lines
9.2 KiB
PHP
248 lines
9.2 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}“.");
|
||
}
|
||
|
||
// Schlüssel und Tokens nur über HTTPS – sonst ließen sie sich unterwegs austauschen
|
||
if (! self::secureUrl($document[$field])) {
|
||
throw new IdentityException("„{$field}“ des Anmeldedienstes muss mit https:// beginnen.");
|
||
}
|
||
}
|
||
|
||
// 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();
|
||
}
|
||
|
||
/** https – nur auf dem eigenen Rechner (Entwicklung) auch http */
|
||
public static function secureUrl(string $url): bool
|
||
{
|
||
return str_starts_with(strtolower($url), 'https://')
|
||
|| (app()->environment('local', 'testing') && preg_match('#^http://(localhost|127\.0\.0\.1)(:\d+)?(/|$)#i', $url));
|
||
}
|
||
}
|