Phase 6 (Teil 2): OpenID Connect, LDAP/AD und SAML 2
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

- 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>
This commit is contained in:
Friederich Loheide 2026-09-26 12:38:32 +00:00
parent 0ab0838050
commit 4fcc41ed30
172 changed files with 18940 additions and 293 deletions

View file

@ -0,0 +1,244 @@
<?php
namespace Inhaus\Plugins\Saml;
use App\Http\Controllers\Auth\IdentityLoginController;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use OneLogin\Saml2\Auth;
use OneLogin\Saml2\Constants;
use OneLogin\Saml2\IdPMetadataParser;
use OneLogin\Saml2\Response;
use OneLogin\Saml2\Settings;
use Throwable;
/**
* SAML 2 als Service Provider (Web-Browser-SSO, HTTP-Redirect hin, HTTP-POST zurück).
*
* Sicherheit: Assertions müssen signiert sein, Antworten müssen zu einer Anfrage
* dieses Portals gehören (InResponseTo, einmalig) und jede Assertion zählt nur einmal.
* Die Anfrage-Kennung liegt im Cache statt in der Sitzung, weil Browser das
* Sitzungs-Cookie beim POST vom Anbieter (anderer Ursprung) nicht mitsenden.
*/
class SamlService
{
public const REQUEST_TTL = 600;
public const NAME_ID_FORMATS = [
Constants::NAMEID_UNSPECIFIED => 'Nicht festgelegt',
Constants::NAMEID_PERSISTENT => 'Dauerhaft (persistent)',
Constants::NAMEID_EMAIL_ADDRESS => 'E-Mail-Adresse',
];
public function entityId(IdentityProvider $provider): string
{
return url('/auth/'.$provider->slug.'/metadata');
}
public function acsUrl(IdentityProvider $provider): string
{
return IdentityLoginController::callbackUrlFor($provider);
}
/**
* Weiterleitungsadresse zum Anbieter; merkt sich die Anfrage.
*/
public function loginUrl(IdentityProvider $provider, ?string $returnTo): string
{
$auth = new Auth($this->settings($provider));
$url = $auth->login($returnTo ?? '', [], false, false, true);
Cache::put('saml.request.'.$auth->getLastRequestID(), ['provider' => $provider->id], self::REQUEST_TTL);
return $url;
}
/**
* Antwort prüfen. Liefert NameID, Format und Attribute.
*
* @return array{name_id: string, name_id_format: string, attributes: array<string, list<string>>}
*/
public function consume(IdentityProvider $provider, string $encoded): array
{
$settings = new Settings($this->settings($provider));
try {
$response = new Response($settings, $encoded);
} catch (Throwable $e) {
throw new IdentityException('Die Antwort des Anmeldedienstes ist nicht lesbar.', previous: $e);
}
$requestId = (string) $response->document->documentElement->getAttribute('InResponseTo');
$pending = $requestId !== '' ? Cache::pull('saml.request.'.$requestId) : null;
if (($pending['provider'] ?? null) !== $provider->id) {
throw new IdentityException('Die Anmeldung ist abgelaufen oder wurde nicht über dieses Portal gestartet. Bitte erneut versuchen.');
}
if (! $this->asOwnUrl($provider, fn () => $response->isValid($requestId))) {
logger()->warning('SAML-Antwort abgelehnt ('.$provider->name.'): '.$response->getError(false));
throw new IdentityException('Die Anmeldung konnte nicht bestätigt werden. Bitte wenden Sie sich an die Administration.');
}
$assertionId = (string) $response->getAssertionId();
$until = (int) ($response->getAssertionNotOnOrAfter() ?: time() + 3600);
if ($assertionId === '' || ! Cache::add('saml.assertion.'.$provider->id.'.'.$assertionId, true, max(60, $until - time() + 300))) {
throw new IdentityException('Diese Anmeldung wurde bereits verwendet. Bitte erneut anmelden.');
}
$attributes = [];
foreach ([$response->getAttributes(), $response->getAttributesWithFriendlyName()] as $set) {
foreach ($set as $name => $values) {
$attributes[(string) $name] = array_values(array_map('strval', (array) $values));
}
}
return [
'name_id' => (string) $response->getNameId(),
'name_id_format' => (string) $response->getNameIdFormat(),
'attributes' => $attributes,
];
}
public function metadataXml(IdentityProvider $provider): string
{
$settings = new Settings($this->settings($provider), true);
return $settings->getSPMetadata();
}
/**
* Metadaten des Anbieters laden und in Konfigurationswerte übersetzen.
*
* @return array{idp_entity_id: string, idp_sso_url: string, idp_certificates: string}
*/
public function importMetadata(string $url, ?string $entityId = null): array
{
$response = Http::timeout(15)->connectTimeout(5)->get($url);
if (! $response->successful()) {
throw new IdentityException('Metadaten nicht abrufbar (HTTP '.$response->status().').');
}
try {
$info = IdPMetadataParser::parseXML($response->body(), $entityId ?: null);
} catch (Throwable $e) {
throw new IdentityException('Die Metadaten sind kein gültiges SAML-Dokument.', previous: $e);
}
$idp = $info['idp'] ?? [];
$certs = array_merge((array) ($idp['x509certMulti']['signing'] ?? []), isset($idp['x509cert']) ? [$idp['x509cert']] : []);
if (empty($idp['entityId']) || empty($idp['singleSignOnService']['url']) || $certs === []) {
throw new IdentityException('In den Metadaten fehlt der Anbieter, die Anmeldeadresse (HTTP-Redirect) oder das Signaturzertifikat.');
}
return [
'idp_entity_id' => (string) $idp['entityId'],
'idp_sso_url' => (string) $idp['singleSignOnService']['url'],
'idp_certificates' => implode("\n\n", array_map(fn ($c) => self::pem($c), array_unique($certs))),
];
}
/**
* Zertifikate aus einem Textfeld (PEM oder nur Base64, eines oder mehrere).
*
* @return list<string> Base64 ohne Kopfzeilen
*/
public static function certificates(?string $text): array
{
$text = (string) $text;
if (preg_match_all('/-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----/s', $text, $matches)) {
$blocks = $matches[1];
} else {
$blocks = preg_split('/\n\s*\n/', trim($text)) ?: [];
}
return array_values(array_filter(array_map(fn ($b) => preg_replace('/\s+/', '', $b), $blocks)));
}
public static function pem(string $base64): string
{
return "-----BEGIN CERTIFICATE-----\n".chunk_split(preg_replace('/\s+/', '', $base64), 64, "\n").'-----END CERTIFICATE-----';
}
/**
* @return array<string, mixed>
*/
public function settings(IdentityProvider $provider): array
{
$certificates = self::certificates($provider->setting('idp_certificates'));
return [
'strict' => true,
'debug' => false,
'sp' => [
'entityId' => $this->entityId($provider),
'assertionConsumerService' => ['url' => $this->acsUrl($provider), 'binding' => Constants::BINDING_HTTP_POST],
'NameIDFormat' => $provider->setting('name_id_format') ?: Constants::NAMEID_UNSPECIFIED,
'x509cert' => '',
'privateKey' => '',
],
'idp' => [
'entityId' => (string) $provider->setting('idp_entity_id'),
'singleSignOnService' => ['url' => (string) $provider->setting('idp_sso_url'), 'binding' => Constants::BINDING_HTTP_REDIRECT],
'x509certMulti' => ['signing' => $certificates],
],
'security' => [
'wantAssertionsSigned' => true,
'wantMessagesSigned' => false,
'authnRequestsSigned' => false,
'requestedAuthnContext' => false,
'rejectUnsolicitedResponsesWithInResponseTo' => true,
'wantNameId' => trim((string) $provider->setting('subject_attribute')) === '',
'signatureAlgorithm' => 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
'digestAlgorithm' => 'http://www.w3.org/2001/04/xmlenc#sha256',
'rejectDeprecatedAlgorithm' => true,
],
];
}
/**
* Die Bibliothek vergleicht Destination/Recipient mit der Adresse aus $_SERVER. Dafür
* die eigene ACS-Adresse einsetzen – so passt der Vergleich auch hinter Proxys.
*
* @template T
*
* @param callable(): T $callback
* @return T
*/
private function asOwnUrl(IdentityProvider $provider, callable $callback): mixed
{
$url = parse_url($this->acsUrl($provider));
$https = ($url['scheme'] ?? 'https') === 'https';
$keys = ['HTTP_HOST', 'SERVER_NAME', 'SERVER_PORT', 'HTTPS', 'REQUEST_URI', 'QUERY_STRING', 'SCRIPT_NAME', 'PATH_INFO'];
$backup = array_intersect_key($_SERVER, array_flip($keys));
foreach ($keys as $key) {
unset($_SERVER[$key]);
}
$_SERVER['HTTP_HOST'] = $url['host'] ?? 'localhost';
$_SERVER['SERVER_NAME'] = $url['host'] ?? 'localhost';
$_SERVER['SERVER_PORT'] = (string) ($url['port'] ?? ($https ? 443 : 80));
$_SERVER['HTTPS'] = $https ? 'on' : 'off';
$_SERVER['REQUEST_URI'] = $url['path'] ?? '/';
$_SERVER['SCRIPT_NAME'] = '';
try {
return $callback();
} finally {
foreach ($keys as $key) {
unset($_SERVER[$key]);
}
$_SERVER = $backup + $_SERVER;
}
}
}