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,112 @@
<?php
namespace App\Identity;
use App\Models\IdentityProvider;
/**
* Baut aus den Attributen eines Anbieters (Claims, LDAP-Attribute, SAML-Attribute)
* das normalisierte Profil – gemäß der Attribut-Zuordnung des Anbieters.
*/
final class AttributeProfile
{
/**
* @param array<string, mixed> $attributes
* @param array<string, string> $defaults Grundwerte (display_name, first_name, last_name, email) => Attribut
* @return array<string, mixed>
*/
public static function build(IdentityProvider $provider, array $attributes, array $defaults): array
{
$profile = [];
foreach ($defaults as $field => $attribute) {
$profile[$field] = self::value($attributes, $attribute);
}
foreach ($provider->attributeMap() as $target => $attribute) {
$value = self::value($attributes, $attribute);
if (str_starts_with($target, 'custom.')) {
$profile['custom'][substr($target, 7)] = $value;
} else {
$profile[$target] = $value;
}
}
return $profile;
}
/**
* Wert eines Attributs als Text. Erst exakter Name (auch ohne Groß-/Kleinschreibung,
* wie bei LDAP), dann Pfad mit Punkten für verschachtelte Claims. Listen werden mit
* Komma verbunden.
*
* @param array<string, mixed> $attributes
*/
public static function value(array $attributes, string $name): ?string
{
$value = self::raw($attributes, $name);
if (is_array($value)) {
$value = implode(', ', array_filter(array_map(fn ($v) => is_scalar($v) ? trim((string) $v) : null, $value), fn ($v) => $v !== null && $v !== ''));
} elseif (is_bool($value)) {
$value = $value ? 'ja' : 'nein';
} elseif (! is_scalar($value)) {
$value = null;
}
$value = $value === null ? null : trim((string) $value);
return $value === '' || ($value !== null && ! mb_check_encoding($value, 'UTF-8')) ? null : $value;
}
/**
* Liste von Werten (z. B. Gruppen).
*
* @param array<string, mixed> $attributes
* @return list<string>
*/
public static function values(array $attributes, string $name): array
{
$value = self::raw($attributes, $name);
$list = is_array($value) ? $value : ($value === null ? [] : [$value]);
return array_values(array_filter(array_map(fn ($v) => is_scalar($v) ? trim((string) $v) : '', $list), fn ($v) => $v !== ''));
}
/**
* @param array<string, mixed> $attributes
*/
public static function raw(array $attributes, string $name): mixed
{
if ($name === '') {
return null;
}
if (array_key_exists($name, $attributes)) {
return $attributes[$name];
}
foreach ($attributes as $key => $value) {
if (is_string($key) && strcasecmp($key, $name) === 0) {
return $value;
}
}
if (! str_contains($name, '.')) {
return null;
}
$value = $attributes;
foreach (explode('.', $name) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return null;
}
$value = $value[$segment];
}
return $value;
}
}

View file

@ -0,0 +1,114 @@
<?php
namespace App\Identity\Entra;
use App\Http\Controllers\Auth\IdentityLoginController;
use App\Identity\IdentityDriver;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use App\Models\User;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Microsoft Entra ID – OpenID Connect plus Microsoft Graph (Profil, Gruppen, Foto,
* Hintergrund-Abgleich). Die Formularfelder stehen wegen ihres Umfangs direkt in
* der Admin-Ressource.
*/
class EntraDriver extends IdentityDriver
{
public function __construct(private readonly EntraLogin $login) {}
public function type(): string
{
return IdentityProvider::ENTRA;
}
public function label(): string
{
return 'Microsoft Entra ID';
}
public function description(): string
{
return 'Microsoft 365 / Azure AD mit Gruppen, App-Rollen, Profilfoto und Hintergrund-Abgleich.';
}
public function defaultButtonLabel(IdentityProvider $provider): string
{
return 'Mit Microsoft anmelden';
}
public function connectionSchema(): array
{
return [];
}
public function secretFields(): array
{
return ['client_secret'];
}
public function defaultAttributeMap(): array
{
return EntraAttributes::DEFAULT_MAP;
}
public function attributePattern(): string
{
return EntraAttributes::PATH_PATTERN;
}
public function attributeLabel(): string
{
return 'Graph-Attribut';
}
public function supportsManager(): bool
{
return true;
}
public function supportsPhoto(): bool
{
return true;
}
public function supportsAppRoles(): bool
{
return true;
}
public function groupValueLabel(): string
{
return 'Objekt-ID der Gruppe';
}
public function start(IdentityProvider $provider, Request $request): Response
{
$start = $this->login->start($provider, IdentityLoginController::callbackUrlFor($provider));
$request->session()->put('identity_login', $start['session']);
return redirect()->away($start['url']);
}
public function complete(IdentityProvider $provider, Request $request): User
{
$session = $request->session()->pull('identity_login');
if ($request->filled('error')) {
// z. B. Abbruch durch die Person oder fehlende Zustimmung in Entra
logger()->notice('Entra-Anmeldung abgebrochen: '.$request->string('error').' '.$request->string('error_description'));
throw new IdentityException($request->string('error')->toString() === 'access_denied'
? 'Die Anmeldung wurde abgebrochen.'
: 'Microsoft hat die Anmeldung abgelehnt. Bitte wenden Sie sich an die Administration.');
}
if (! is_array($session) || ! hash_equals($session['state'] ?? '', (string) $request->query('state')) || ($session['provider'] ?? null) !== (string) $provider->id) {
throw new IdentityException('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.');
}
return $this->login->complete($provider, (string) $request->query('code'), IdentityLoginController::callbackUrlFor($provider), $session);
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Identity;
/**
* Eine beim Anbieter bestätigte Identität – so, wie sie der Kern weiterverarbeitet.
*/
final class ExternalUser
{
/**
* @param string $subject dauerhafte, eindeutige Kennung beim Anbieter
* @param array<string, mixed> $profile normalisiert (display_name, first_name, email, custom …), siehe AttributeProfile
* @param list<string> $groups Gruppenwerte für die Rollen-Zuordnung
* @param list<string> $appRoles
* @param array<string, mixed> $attributes Rohdaten – für „Zuletzt empfangen“ im Admin
* @param string|null|false $photo Binärdaten, null = kein Foto, false = unbekannt/nicht abgleichen
*/
public function __construct(
public readonly string $subject,
public readonly array $profile,
public readonly array $groups = [],
public readonly array $appRoles = [],
public readonly array $attributes = [],
public readonly string|null|false $photo = false,
) {}
}

View file

@ -0,0 +1,167 @@
<?php
namespace App\Identity;
use App\Models\IdentityProvider;
use App\Models\User;
use Filament\Actions\Action;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Ein Anmeldeverfahren (Entra ID, OpenID Connect, LDAP, SAML …). Plugins melden
* weitere Verfahren über App\Identity\IdentityDrivers an.
*
* Ablauf: start() leitet zum Anbieter weiter oder zeigt ein eigenes Formular;
* complete() wertet die Rückkehr aus. Die meisten Verfahren liefern dafür nur
* authenticate() – Konto, Profil und Rollen übernimmt der Kern (IdentityLogin).
*/
abstract class IdentityDriver
{
/** Kürzel, wie es in identity_providers.type steht. */
abstract public function type(): string;
/** z. B. „OpenID Connect“ */
abstract public function label(): string;
public function description(): string
{
return '';
}
public function defaultButtonLabel(IdentityProvider $provider): string
{
return 'Mit '.$provider->name.' anmelden';
}
/**
* Grund, warum das Verfahren auf diesem Server nicht nutzbar ist (z. B. fehlende
* PHP-Erweiterung) – oder null.
*/
public function unavailableReason(): ?string
{
return null;
}
/**
* Filament-Felder für die Verbindung (Speicherort: config.*).
*
* @return list<mixed>
*/
abstract public function connectionSchema(): array;
/** Hinweistext über den Verbindungsfeldern (HTML erlaubt, bereits escaped). */
public function connectionHelp(?IdentityProvider $provider): string
{
return '';
}
/**
* Zusätzliche Aktionen am Verbindungsabschnitt im Admin (z. B. „Verbindung testen“).
* Werden nur beim Bearbeiten angezeigt.
*
* @return list<Action>
*/
public function adminActions(): array
{
return [];
}
/**
* Konfigurationswerte, die nie ins Formular gelangen und beim Speichern mit
* leerem Feld erhalten bleiben.
*
* @return list<string>
*/
public function secretFields(): array
{
return [];
}
/**
* Standardzuordnung Profilfeld => Attribut für neue Anbieter.
*
* @return array<string, string>
*/
public function defaultAttributeMap(): array
{
return [];
}
/**
* Vorschläge für die Attributauswahl: Attribut => Bezeichnung.
*
* @return array<string, string>
*/
public function attributeSuggestions(?IdentityProvider $provider): array
{
return [];
}
/** Erlaubte Attributnamen – großzügig, weil SAML URIs und LDAP Bindestriche nutzt. */
public function attributePattern(): string
{
return '/^[^\s<>"\'\\\\]{1,191}$/';
}
public function attributeLabel(): string
{
return 'Attribut';
}
public function supportsManager(): bool
{
return false;
}
public function supportsPhoto(): bool
{
return false;
}
public function supportsAppRoles(): bool
{
return false;
}
/** Beschriftung für den Wert einer Gruppe in der Rollen-Zuordnung. */
public function groupValueLabel(): string
{
return 'Gruppe (Wert wie übermittelt)';
}
/** Anmeldung beginnen: Weiterleitung zum Anbieter oder eigenes Formular. */
abstract public function start(IdentityProvider $provider, Request $request): Response;
/**
* Rückkehr bzw. Formular auswerten und die angemeldete Person liefern.
*
* @throws IdentityException mit einer Meldung für die Person
*/
public function complete(IdentityProvider $provider, Request $request): User
{
return app(IdentityLogin::class)->finish($provider, $this->authenticate($provider, $request));
}
/**
* Identität beim Anbieter bestätigen.
*
* @throws IdentityException
*/
protected function authenticate(IdentityProvider $provider, Request $request): ExternalUser
{
throw new IdentityException('Dieses Anmeldeverfahren ist nicht vollständig eingerichtet.');
}
/** Wohin es nach der Anmeldung geht (z. B. aus einem RelayState) – null = gemerkte Seite. */
public function intendedUrl(IdentityProvider $provider, Request $request): ?string
{
return null;
}
/** Zusätzliche öffentliche Antwort, z. B. SAML-Metadaten. */
public function metadata(IdentityProvider $provider): ?Response
{
return null;
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace App\Identity;
use Illuminate\Contracts\Container\Container;
/**
* Registry der Anmeldeverfahren. Der Kern bringt Entra ID mit, Plugins melden
* weitere an: $drivers->add('oidc', OidcDriver::class).
*/
class IdentityDrivers
{
/** @var array<string, class-string<IdentityDriver>> */
private array $classes = [];
/** @var array<string, IdentityDriver> */
private array $instances = [];
public function __construct(private readonly Container $container) {}
/**
* @param class-string<IdentityDriver> $class
*/
public function add(string $type, string $class): void
{
$this->classes[$type] = $class;
unset($this->instances[$type]);
}
public function has(string $type): bool
{
return isset($this->classes[$type]);
}
public function get(string $type): ?IdentityDriver
{
if (! isset($this->classes[$type])) {
return null;
}
return $this->instances[$type] ??= $this->container->make($this->classes[$type]);
}
/**
* @return array<string, IdentityDriver>
*/
public function all(): array
{
$all = [];
foreach (array_keys($this->classes) as $type) {
$all[$type] = $this->get($type);
}
return $all;
}
}

View file

@ -0,0 +1,86 @@
<?php
namespace App\Identity;
use App\Models\IdentityProvider;
use App\Models\User;
use App\Models\UserIdentity;
use Illuminate\Support\Facades\Cache;
/**
* Gemeinsamer Abschluss jeder Anmeldung über einen Anbieter: Konto finden oder
* anlegen, Profil, Rollen und Foto übernehmen.
*/
class IdentityLogin
{
public const LAST_SEEN_TTL = 60 * 60 * 24 * 14;
public function __construct(private readonly IdentitySync $sync) {}
public function finish(IdentityProvider $provider, ExternalUser $external): User
{
self::remember($provider, $external);
$user = $this->sync->resolveUser($provider, $external->subject, $external->profile, (bool) $provider->setting('auto_provision', true));
if (! $user) {
throw new IdentityException('Für Ihr Konto bei „'.$provider->name.'“ gibt es kein Konto in diesem Portal. Bitte wenden Sie sich an die Administration.');
}
if (! $user->is_active) {
throw new IdentityException('Ihr Konto ist deaktiviert. Bitte wenden Sie sich an die Administration.');
}
$identity = UserIdentity::query()->where('identity_provider_id', $provider->id)->where('subject', $external->subject)->firstOrFail();
$identity->update(['last_login_at' => now(), 'email' => $external->profile['email'] ?? $identity->email]);
$this->sync->syncProfile($provider, $user, $external->profile);
$this->sync->syncRoles($provider, $user, $external->groups, $external->appRoles);
if ($external->photo !== false && $provider->setting('sync_photo', false)) {
$this->sync->syncPhoto($identity->fresh('user'), $external->photo);
}
return $user->fresh();
}
/**
* Zuletzt empfangene Angaben für die Administration (Hilfe bei der Zuordnung).
*/
public static function remember(IdentityProvider $provider, ExternalUser $external): void
{
$attributes = [];
foreach ($external->attributes as $key => $value) {
if (count($attributes) >= 80) {
break;
}
$text = is_array($value) && ! array_is_list($value)
? (string) json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
: (is_array($value)
? implode(', ', array_slice(array_map(fn ($v) => is_scalar($v) ? (string) $v : json_encode($v), $value), 0, 20))
: (is_scalar($value) || $value === null ? (string) $value : json_encode($value)));
// Binärwerte (Fotos, GUIDs) nicht speichern.
$attributes[(string) $key] = mb_check_encoding($text, 'UTF-8') ? mb_strimwidth($text, 0, 300, '…') : '(Binärdaten)';
}
Cache::put('identity.last_seen.'.$provider->id, [
'at' => now()->timestamp,
'subject' => $external->subject,
'attributes' => $attributes,
'groups' => array_slice($external->groups, 0, 100),
], self::LAST_SEEN_TTL);
}
/**
* @return array{at: int, subject: string, attributes: array<string, string>, groups: list<string>}|null
*/
public static function lastSeen(IdentityProvider $provider): ?array
{
$value = Cache::get('identity.last_seen.'.$provider->id);
return is_array($value) ? $value : null;
}
}

View file

@ -57,7 +57,7 @@ class IdentitySync
}
if (! $email) {
throw new IdentityException('Für dieses Microsoft-Konto ist keine E-Mail-Adresse hinterlegt.');
throw new IdentityException('Für Ihr Konto ist beim Anmeldedienst keine E-Mail-Adresse hinterlegt.');
}
$user = User::query()->create([