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,13 @@
{
"slug": "ldap",
"name": "Anmeldung: LDAP / Active Directory",
"version": "1.0.0",
"description": "Anmeldung mit Benutzername und Passwort gegen ein lokales Active Directory oder OpenLDAP – mit Gruppen (auch verschachtelt), Profil, Vorgesetzten und Foto. Benötigt die PHP-Erweiterung „ldap“.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Ldap\\",
"class": "Inhaus\\Plugins\\Ldap\\LdapPlugin",
"requires": {
"core": ">=0.9.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Inhaus\Plugins\Ldap\Connection;
/**
* Eine Verbindung zum Verzeichnis. Einträge kommen normalisiert zurück:
* ['dn' => '…', 'attributes' => ['kleingeschriebener name' => list<string>]].
*/
interface LdapConnection
{
/** Anmelden; null/null = anonym. false bei falschen Zugangsdaten. */
public function bind(?string $dn, ?string $password): bool;
/**
* @param list<string> $attributes
* @return list<array{dn: string, attributes: array<string, list<string>>}>
*/
public function search(string $base, string $filter, array $attributes, int $limit = 0): array;
/**
* Einen Eintrag direkt lesen.
*
* @param list<string> $attributes
* @return array{dn: string, attributes: array<string, list<string>>}|null
*/
public function read(string $dn, array $attributes): ?array;
public function lastError(): string;
}

View file

@ -0,0 +1,11 @@
<?php
namespace Inhaus\Plugins\Ldap\Connection;
interface LdapConnector
{
/**
* @param array{hosts: list<string>, port: ?int, encryption: string, verify_tls: bool, timeout: int} $options
*/
public function connect(array $options): LdapConnection;
}

View file

@ -0,0 +1,78 @@
<?php
namespace Inhaus\Plugins\Ldap\Connection;
use App\Identity\IdentityException;
use LDAP\Connection;
class NativeLdapConnection implements LdapConnection
{
/** Ungültige Zugangsdaten – alles andere ist ein Verbindungs- oder Serverfehler. */
private const INVALID_CREDENTIALS = 49;
public function __construct(private readonly Connection $link) {}
public function bind(?string $dn, ?string $password): bool
{
if (@ldap_bind($this->link, $dn, $password)) {
return true;
}
if (ldap_errno($this->link) === self::INVALID_CREDENTIALS) {
return false;
}
throw new IdentityException('Der Verzeichnisserver ist nicht erreichbar: '.ldap_error($this->link));
}
public function search(string $base, string $filter, array $attributes, int $limit = 0): array
{
$result = @ldap_search($this->link, $base, $filter, $attributes, 0, $limit);
// 4 = Größenlimit erreicht: Teilergebnis ist in Ordnung.
if ($result === false && ldap_errno($this->link) !== 4) {
throw new IdentityException('Suche im Verzeichnis fehlgeschlagen: '.ldap_error($this->link));
}
return $result === false ? [] : $this->entries($result);
}
public function read(string $dn, array $attributes): ?array
{
$result = @ldap_read($this->link, $dn, '(objectClass=*)', $attributes);
return $result === false ? null : ($this->entries($result)[0] ?? null);
}
public function lastError(): string
{
return ldap_error($this->link);
}
/**
* @return list<array{dn: string, attributes: array<string, list<string>>}>
*/
private function entries($result): array
{
$entries = [];
for ($entry = ldap_first_entry($this->link, $result); $entry !== false; $entry = ldap_next_entry($this->link, $entry)) {
$attributes = [];
foreach (ldap_get_attributes($this->link, $entry) as $name => $values) {
if (! is_string($name) || ! is_array($values) || $name === 'count') {
continue;
}
// Binärwerte (objectGUID, thumbnailPhoto) unverändert lesen.
$raw = @ldap_get_values_len($this->link, $entry, $name) ?: [];
unset($raw['count']);
$attributes[strtolower($name)] = array_values($raw);
}
$entries[] = ['dn' => (string) ldap_get_dn($this->link, $entry), 'attributes' => $attributes];
}
return $entries;
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Inhaus\Plugins\Ldap\Connection;
use App\Identity\IdentityException;
use LDAP\Connection;
/**
* Verbindung über die PHP-Erweiterung „ldap“.
*/
class NativeLdapConnector implements LdapConnector
{
public function connect(array $options): LdapConnection
{
if (! function_exists('ldap_connect')) {
throw new IdentityException('Die PHP-Erweiterung „ldap“ ist auf diesem Server nicht installiert.');
}
$scheme = $options['encryption'] === 'ldaps' ? 'ldaps' : 'ldap';
$port = $options['port'] ?: ($scheme === 'ldaps' ? 636 : 389);
$uris = implode(' ', array_map(fn ($host) => str_contains($host, '://') ? $host : "{$scheme}://{$host}:{$port}", $options['hosts']));
if (! $options['verify_tls']) {
// Muss vor ldap_connect gesetzt werden, damit es für die Verbindung gilt.
ldap_set_option(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
}
$link = ldap_connect($uris);
if (! $link instanceof Connection) {
throw new IdentityException('Die Adresse des Verzeichnisservers ist ungültig.');
}
ldap_set_option($link, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($link, LDAP_OPT_REFERRALS, 0);
ldap_set_option($link, LDAP_OPT_NETWORK_TIMEOUT, $options['timeout']);
ldap_set_option($link, LDAP_OPT_TIMELIMIT, $options['timeout']);
if ($options['encryption'] === 'starttls' && ! @ldap_start_tls($link)) {
throw new IdentityException('Verschlüsselte Verbindung (StartTLS) zum Verzeichnis fehlgeschlagen: '.ldap_error($link));
}
return new NativeLdapConnection($link);
}
}

View file

@ -0,0 +1,289 @@
<?php
namespace Inhaus\Plugins\Ldap;
use App\Identity\AttributeProfile;
use App\Identity\ExternalUser;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Inhaus\Plugins\Ldap\Connection\LdapConnection;
use Inhaus\Plugins\Ldap\Connection\LdapConnector;
/**
* Anmeldung und Abfragen gegen Active Directory bzw. OpenLDAP.
*
* Ablauf: mit dem Dienstkonto verbinden, Person über den Filter suchen, mit ihrem
* DN und Passwort anmelden (prüft das Passwort), danach Gruppen, Vorgesetzte*n und
* Foto mit dem Dienstkonto lesen.
*/
class LdapDirectory
{
public const PRESETS = [
'ad' => [
'user_filter' => '(&(objectCategory=person)(objectClass=user)(|(sAMAccountName={username})(userPrincipalName={username})(mail={username})))',
'uid_attribute' => 'objectGUID',
'photo_attribute' => 'thumbnailPhoto',
'group_filter' => '(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={dn}))',
],
'openldap' => [
'user_filter' => '(&(objectClass=inetOrgPerson)(|(uid={username})(mail={username})))',
'uid_attribute' => 'entryUUID',
'photo_attribute' => 'jpegPhoto',
'group_filter' => '(|(&(objectClass=groupOfNames)(member={dn}))(&(objectClass=groupOfUniqueNames)(uniqueMember={dn}))(&(objectClass=posixGroup)(memberUid={username})))',
],
];
public const DEFAULT_MAPS = [
'ad' => [
'first_name' => 'givenName', 'last_name' => 'sn', 'email' => 'mail', 'job_title' => 'title',
'department' => 'department', 'location' => 'physicalDeliveryOfficeName', 'phone' => 'telephoneNumber', 'mobile' => 'mobile',
],
'openldap' => [
'first_name' => 'givenName', 'last_name' => 'sn', 'email' => 'mail', 'job_title' => 'title',
'department' => 'ou', 'location' => 'l', 'phone' => 'telephoneNumber', 'mobile' => 'mobile',
],
];
/** Attribute, die nie als Text gespeichert oder angezeigt werden. */
private const BINARY = ['objectguid', 'objectsid', 'thumbnailphoto', 'jpegphoto', 'usercertificate', 'msexchmailboxguid', 'msexchmailboxsecuritydescriptor'];
private const SECRET = ['userpassword', 'unicodepwd', 'ntpassword', 'lmpassword'];
public function __construct(private readonly LdapConnector $connector) {}
public function authenticate(IdentityProvider $provider, string $username, string $password): ExternalUser
{
$username = trim($username);
if ($username === '' || $password === '' || str_contains($username, "\0")) {
throw new IdentityException('Benutzername oder Passwort ist falsch.');
}
$connection = $this->connectAsService($provider);
$entry = $this->findUser($connection, $provider, $username);
// Leeres Passwort wäre eine anonyme Anmeldung – oben ausgeschlossen.
if (! $entry || ! $connection->bind($entry['dn'], $password)) {
throw new IdentityException('Benutzername oder Passwort ist falsch.');
}
if ($this->isDisabled($entry)) {
throw new IdentityException('Ihr Konto ist im Verzeichnis deaktiviert. Bitte wenden Sie sich an die Administration.');
}
// Für Gruppen und Vorgesetzte wieder als Dienstkonto.
$this->bindService($connection, $provider);
return $this->toExternal($connection, $provider, $entry, $username);
}
/**
* Für „Verbindung testen“ im Admin: Dienstkonto prüfen und optional eine Person
* nachschlagen (ohne Passwort).
*
* @return array{user: ?ExternalUser, dn: ?string}
*/
public function test(IdentityProvider $provider, ?string $username): array
{
$connection = $this->connectAsService($provider);
if ($username === null || trim($username) === '') {
return ['user' => null, 'dn' => null];
}
$entry = $this->findUser($connection, $provider, trim($username));
if (! $entry) {
throw new IdentityException('Verbindung in Ordnung, aber „'.trim($username).'“ wurde mit dem Suchfilter nicht gefunden.');
}
return ['user' => $this->toExternal($connection, $provider, $entry, trim($username)), 'dn' => $entry['dn']];
}
public function connectAsService(IdentityProvider $provider): LdapConnection
{
$hosts = preg_split('/[\s,;]+/', (string) $provider->setting('hosts'), -1, PREG_SPLIT_NO_EMPTY) ?: [];
if ($hosts === [] || trim((string) $provider->setting('base_dn')) === '') {
throw new IdentityException('Die LDAP-Anmeldung ist nicht vollständig eingerichtet.');
}
$connection = $this->connector->connect([
'hosts' => $hosts,
'port' => ((int) $provider->setting('port')) ?: null,
'encryption' => (string) $provider->setting('encryption', 'ldaps'),
'verify_tls' => (bool) $provider->setting('verify_tls', true),
'timeout' => 8,
]);
$this->bindService($connection, $provider);
return $connection;
}
/**
* @return array{dn: string, attributes: array<string, list<string>>}|null
*/
public function findUser(LdapConnection $connection, IdentityProvider $provider, string $username): ?array
{
$filter = str_replace('{username}', self::escape($username), $this->setting($provider, 'user_filter'));
$entries = $connection->search((string) $provider->setting('base_dn'), $filter, ['*', '+', $this->setting($provider, 'uid_attribute')], 2);
// Mehrdeutige Treffer nie anmelden.
return count($entries) === 1 ? $entries[0] : null;
}
public function setting(IdentityProvider $provider, string $key): string
{
$value = trim((string) $provider->setting($key));
return $value !== '' ? $value : (self::PRESETS[$this->schema($provider)][$key] ?? '');
}
public function schema(IdentityProvider $provider): string
{
return $provider->setting('schema') === 'openldap' ? 'openldap' : 'ad';
}
/**
* Wert für einen LDAP-Filter maskieren (RFC 4515).
*/
public static function escape(string $value): string
{
return strtr($value, ['\\' => '\5c', '*' => '\2a', '(' => '\28', ')' => '\29', "\0" => '\00']);
}
/**
* objectGUID (binär, gemischte Byte-Reihenfolge) als Text.
*/
public static function guid(string $binary): string
{
if (strlen($binary) !== 16) {
return $binary;
}
$hex = unpack('Va/v2b/n2c/Nd', $binary);
return sprintf('%08x-%04x-%04x-%04x-%04x%08x', $hex['a'], $hex['b1'], $hex['b2'], $hex['c1'], $hex['c2'], $hex['d']);
}
private function bindService(LdapConnection $connection, IdentityProvider $provider): void
{
$dn = trim((string) $provider->setting('bind_dn'));
if (! $connection->bind($dn !== '' ? $dn : null, $dn !== '' ? (string) $provider->setting('bind_password') : null)) {
throw new IdentityException('Das Dienstkonto für das Verzeichnis wurde abgelehnt. Bitte wenden Sie sich an die Administration.');
}
}
/**
* @param array{dn: string, attributes: array<string, list<string>>} $entry
*/
private function isDisabled(array $entry): bool
{
$control = (int) ($entry['attributes']['useraccountcontrol'][0] ?? 0);
return ($control & 2) === 2;
}
/**
* @param array{dn: string, attributes: array<string, list<string>>} $entry
*/
private function subject(IdentityProvider $provider, array $entry): string
{
$attribute = strtolower($this->setting($provider, 'uid_attribute'));
$value = $entry['attributes'][$attribute][0] ?? null;
if ($value === null || $value === '') {
throw new IdentityException('Im Verzeichnis fehlt die eindeutige Kennung („'.$this->setting($provider, 'uid_attribute').'“).');
}
return $attribute === 'objectguid' ? self::guid($value) : $value;
}
/**
* @param array{dn: string, attributes: array<string, list<string>>} $entry
*/
private function toExternal(LdapConnection $connection, IdentityProvider $provider, array $entry, string $username): ExternalUser
{
$attributes = array_diff_key($entry['attributes'], array_flip(self::SECRET));
$text = array_diff_key($attributes, array_flip(self::BINARY));
$text['dn'] = [$entry['dn']];
$profile = AttributeProfile::build($provider, $text, [
'display_name' => 'displayName',
'first_name' => 'givenName',
'last_name' => 'sn',
'email' => 'mail',
]);
if ($provider->syncsManager()) {
$profile['manager_subject'] = $this->managerSubject($connection, $provider, $attributes['manager'][0] ?? null);
}
$photo = false;
if ($provider->setting('sync_photo', false)) {
$photo = $attributes[strtolower($this->setting($provider, 'photo_attribute'))][0] ?? null;
}
return new ExternalUser(
subject: $this->subject($provider, $entry),
profile: $profile,
groups: $this->groups($connection, $provider, $entry, $username),
attributes: $text,
photo: $photo,
);
}
/**
* Gruppen-DNs: direkt aus memberOf und – falls eingestellt – über eine Gruppensuche
* (AD: inklusive verschachtelter Gruppen).
*
* @param array{dn: string, attributes: array<string, list<string>>} $entry
* @return list<string>
*/
private function groups(LdapConnection $connection, IdentityProvider $provider, array $entry, string $username): array
{
$groups = $entry['attributes']['memberof'] ?? [];
if ($provider->setting('group_search', true)) {
$filter = strtr($this->setting($provider, 'group_filter'), [
'{dn}' => self::escape($entry['dn']),
'{username}' => self::escape($username),
]);
$base = trim((string) $provider->setting('group_base_dn')) ?: (string) $provider->setting('base_dn');
try {
foreach ($connection->search($base, $filter, ['dn'], 1000) as $group) {
$groups[] = $group['dn'];
}
} catch (IdentityException $e) {
logger()->warning('LDAP-Gruppensuche fehlgeschlagen: '.$e->getMessage());
}
}
$unique = [];
foreach ($groups as $dn) {
$unique[strtolower($dn)] ??= $dn;
}
return array_values($unique);
}
private function managerSubject(LdapConnection $connection, IdentityProvider $provider, ?string $managerDn): ?string
{
if (! $managerDn) {
return null;
}
$entry = $connection->read($managerDn, [$this->setting($provider, 'uid_attribute')]);
try {
return $entry ? $this->subject($provider, $entry) : null;
} catch (IdentityException) {
return null;
}
}
}

View file

@ -0,0 +1,196 @@
<?php
namespace Inhaus\Plugins\Ldap;
use App\Identity\ExternalUser;
use App\Identity\IdentityDriver;
use App\Models\IdentityProvider;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Support\Icons\Heroicon;
use Illuminate\Http\Request;
use Illuminate\Support\HtmlString;
use Inertia\Inertia;
use Inhaus\Plugins\Ldap\Connection\LdapConnector;
use Inhaus\Plugins\Ldap\Connection\NativeLdapConnector;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Anmeldung mit Benutzername und Passwort gegen Active Directory oder OpenLDAP.
*/
class LdapDriver extends IdentityDriver
{
public const TYPE = 'ldap';
public function __construct(private readonly LdapDirectory $directory) {}
public function type(): string
{
return self::TYPE;
}
public function label(): string
{
return 'LDAP / Active Directory';
}
public function description(): string
{
return 'Lokales Active Directory oder OpenLDAP – Anmeldung mit dem Windows- bzw. Verzeichnis-Passwort.';
}
public function defaultButtonLabel(IdentityProvider $provider): string
{
return 'Mit Firmenkonto anmelden';
}
public function unavailableReason(): ?string
{
return function_exists('ldap_connect') || ! app(LdapConnector::class) instanceof NativeLdapConnector
? null
: 'Die PHP-Erweiterung „ldap“ ist auf diesem Server nicht installiert. Bitte beim Hoster aktivieren lassen.';
}
public function connectionHelp(?IdentityProvider $provider): string
{
return 'Das Portal meldet sich mit einem Dienstkonto (nur Leserechte) am Verzeichnis an, sucht die Person und prüft dann ihr Passwort. '
.'Die Verbindung sollte verschlüsselt sein (LDAPS oder StartTLS) – Passwörter gehen sonst im Klartext über das Netz.';
}
public function connectionSchema(): array
{
return [
Select::make('config.schema')->label('Verzeichnis')->native(false)->required()->default('ad')->selectablePlaceholder(false)->live()
->options(['ad' => 'Microsoft Active Directory', 'openldap' => 'OpenLDAP / andere']),
TextInput::make('config.hosts')->label('Server')->required()->maxLength(500)
->placeholder('dc1.firma.local dc2.firma.local')
->helperText('Mehrere Server mit Leerzeichen trennen – der nächste wird genutzt, wenn einer ausfällt.'),
Select::make('config.encryption')->label('Verschlüsselung')->native(false)->required()->default('ldaps')->selectablePlaceholder(false)
->options(['ldaps' => 'LDAPS (Port 636)', 'starttls' => 'StartTLS (Port 389)', 'none' => 'Keine – nicht empfohlen']),
TextInput::make('config.port')->label('Port')->numeric()->minValue(1)->maxValue(65535)->placeholder('Standard'),
Toggle::make('config.verify_tls')->label('Zertifikat des Servers prüfen')->default(true)
->helperText('Nur für Tests mit selbst signierten Zertifikaten ausschalten.')->columnSpanFull(),
TextInput::make('config.base_dn')->label('Suchbasis (Base DN)')->required()->maxLength(500)->placeholder('DC=firma,DC=local')->columnSpanFull(),
TextInput::make('config.bind_dn')->label('Dienstkonto (DN oder UPN)')->maxLength(500)->placeholder('CN=svc-portal,OU=Dienste,DC=firma,DC=local'),
TextInput::make('config.bind_password')->label('Passwort des Dienstkontos')->password()->revealable()->maxLength(1000)
->helperText(fn (string $operation) => $operation === 'edit' ? 'Leer lassen, um das gespeicherte Passwort zu behalten.' : null),
TextInput::make('config.user_filter')->label('Suchfilter für Personen')->maxLength(1000)->columnSpanFull()
->placeholder(fn (Get $get) => LdapDirectory::PRESETS[$get('config.schema') === 'openldap' ? 'openldap' : 'ad']['user_filter'])
->helperText('{username} steht für die Eingabe. Leer = Standard für das gewählte Verzeichnis.'),
TextInput::make('config.uid_attribute')->label('Eindeutige Kennung')->maxLength(100)
->placeholder(fn (Get $get) => LdapDirectory::PRESETS[$get('config.schema') === 'openldap' ? 'openldap' : 'ad']['uid_attribute'])
->helperText('Darf sich nie ändern – nicht den Benutzernamen verwenden.'),
TextInput::make('config.username_label')->label('Beschriftung des Benutzernamens')->maxLength(60)->placeholder('Benutzername'),
Toggle::make('config.group_search')->label('Gruppen zusätzlich suchen')->default(true)->live()
->helperText('AD: inklusive verschachtelter Gruppen. Sonst zählt nur memberOf.'),
TextInput::make('config.group_base_dn')->label('Suchbasis für Gruppen')->maxLength(500)->placeholder('wie oben')
->visible(fn (Get $get) => (bool) $get('config.group_search')),
TextInput::make('config.group_filter')->label('Suchfilter für Gruppen')->maxLength(1000)->columnSpanFull()
->placeholder(fn (Get $get) => LdapDirectory::PRESETS[$get('config.schema') === 'openldap' ? 'openldap' : 'ad']['group_filter'])
->helperText('{dn} = DN der Person, {username} = Eingabe. Leer = Standard.')
->visible(fn (Get $get) => (bool) $get('config.group_search')),
];
}
public function adminActions(): array
{
return [
Action::make('testLdap')->label('Verbindung testen')->icon(Heroicon::OutlinedSignal)->color('gray')->size('sm')
->modalHeading('Verbindung zum Verzeichnis testen')
->modalDescription('Prüft das Dienstkonto mit den gespeicherten Einstellungen. Mit Benutzername zeigt der Test, welche Angaben und Gruppen das Portal erhält – ohne Passwort, ohne Anmeldung.')
->modalSubmitActionLabel('Testen')
->schema([TextInput::make('username')->label('Benutzername (optional)')->maxLength(191)])
->action(function (array $data, IdentityProvider $record, Action $action) {
try {
$result = $this->directory->test($record, $data['username'] ?? null);
} catch (Throwable $e) {
Notification::make()->danger()->title('Test fehlgeschlagen')->body($e->getMessage())->persistent()->send();
$action->halt();
return;
}
if (! $result['user']) {
Notification::make()->success()->title('Verbindung und Dienstkonto in Ordnung')->send();
return;
}
Notification::make()->success()->persistent()->title('Gefunden: '.$result['dn'])
->body(new HtmlString(self::summary($result['user'])))->send();
}),
];
}
public function secretFields(): array
{
return ['bind_password'];
}
public function defaultAttributeMap(): array
{
return LdapDirectory::DEFAULT_MAPS['ad'];
}
public function attributeSuggestions(?IdentityProvider $provider): array
{
return [
'givenName' => 'Vorname', 'sn' => 'Nachname', 'displayName' => 'Anzeigename', 'mail' => 'E-Mail',
'title' => 'Funktion', 'department' => 'Abteilung', 'company' => 'Firma', 'physicalDeliveryOfficeName' => 'Büro',
'l' => 'Ort', 'telephoneNumber' => 'Telefon', 'mobile' => 'Mobil', 'employeeID' => 'Personalnummer (AD)',
'employeeNumber' => 'Personalnummer', 'sAMAccountName' => 'Anmeldename (AD)', 'uid' => 'Benutzername (OpenLDAP)',
'extensionAttribute1' => 'Erweiterungsattribut 1 (AD)', 'extensionAttribute2' => 'Erweiterungsattribut 2 (AD)',
];
}
public function supportsManager(): bool
{
return true;
}
public function supportsPhoto(): bool
{
return true;
}
public function groupValueLabel(): string
{
return 'DN der Gruppe';
}
public function start(IdentityProvider $provider, Request $request): Response
{
return Inertia::render('Auth/DirectoryLogin', [
'provider' => [
'name' => $provider->name,
'label' => $provider->buttonLabel(),
'action' => route('identity.login', $provider),
'username_label' => $provider->setting('username_label') ?: 'Benutzername',
],
])->toResponse($request);
}
protected function authenticate(IdentityProvider $provider, Request $request): ExternalUser
{
return $this->directory->authenticate($provider, (string) $request->input('username'), (string) $request->input('password'));
}
public static function summary(ExternalUser $user): string
{
$rows = collect($user->profile)->except('custom')->filter(fn ($v) => is_scalar($v) && $v !== '')
->map(fn ($v, $k) => e($k).': '.e((string) $v));
$rows->push('Kennung: '.e($user->subject));
$rows->push('Gruppen: '.($user->groups === [] ? 'keine' : e(implode(' · ', array_slice($user->groups, 0, 15)))));
if ($user->photo !== false) {
$rows->push('Foto: '.($user->photo ? 'vorhanden' : 'keins'));
}
return $rows->implode('<br>');
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\Ldap;
use App\Identity\IdentityDrivers;
use App\Plugins\Plugin;
use Inhaus\Plugins\Ldap\Connection\LdapConnector;
use Inhaus\Plugins\Ldap\Connection\NativeLdapConnector;
class LdapPlugin extends Plugin
{
public function register(): void
{
$this->app->bindIf(LdapConnector::class, NativeLdapConnector::class);
$this->app->make(IdentityDrivers::class)->add(LdapDriver::TYPE, LdapDriver::class);
}
}

View file

@ -0,0 +1,13 @@
{
"slug": "oidc",
"name": "Anmeldung: OpenID Connect",
"version": "1.0.0",
"description": "Anmeldung über jeden OpenID-Connect-Anbieter, z. B. Keycloak, Authentik, Okta, Google Workspace oder Univention – mit Gruppen-Zuordnung und Profil-Übernahme.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Oidc\\",
"class": "Inhaus\\Plugins\\Oidc\\OidcPlugin",
"requires": {
"core": ">=0.9.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,236 @@
<?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();
}
}

View file

@ -0,0 +1,182 @@
<?php
namespace Inhaus\Plugins\Oidc;
use App\Http\Controllers\Auth\IdentityLoginController;
use App\Identity\AttributeProfile;
use App\Identity\ExternalUser;
use App\Identity\IdentityDriver;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Anmeldung über einen beliebigen OpenID-Connect-Anbieter.
*/
class OidcDriver extends IdentityDriver
{
public const TYPE = 'oidc';
private const SESSION = 'identity_login';
public function type(): string
{
return self::TYPE;
}
public function label(): string
{
return 'OpenID Connect';
}
public function description(): string
{
return 'Keycloak, Authentik, Okta, Google Workspace, Univention, Nextcloud und alle anderen OIDC-Anbieter.';
}
public function connectionHelp(?IdentityProvider $provider): string
{
$callback = $provider ? IdentityLoginController::callbackUrlFor($provider) : url('/auth/<kürzel>/callback');
return 'Beim Anbieter einen vertraulichen Client (Autorisierungscode-Verfahren) anlegen. Weiterleitungs-URI: <code>'.e($callback).'</code>';
}
public function connectionSchema(): array
{
return [
TextInput::make('config.issuer')->label('Aussteller (Issuer-URL)')->required()->url()->maxLength(255)
->placeholder('https://login.firma.de/realms/mitarbeitende')
->helperText('Die Adresse, unter der /.well-known/openid-configuration liegt.')
->columnSpanFull(),
TextInput::make('config.client_id')->label('Client-ID')->required()->maxLength(255),
TextInput::make('config.client_secret')->label('Client-Geheimnis')->password()->revealable()->maxLength(1000)
->required(fn (string $operation) => $operation === 'create')
->helperText(fn (string $operation) => $operation === 'edit' ? 'Leer lassen, um das gespeicherte Geheimnis zu behalten.' : null),
TextInput::make('config.scopes')->label('Scopes')->default('openid profile email')->maxLength(255)
->helperText('Für Gruppen je nach Anbieter z. B. „groups“ ergänzen.'),
TextInput::make('config.groups_claim')->label('Claim mit den Gruppen')->default('groups')->maxLength(191)
->helperText('z. B. groups, roles oder realm_access.roles (Keycloak).'),
Select::make('config.token_auth')->label('Client-Authentifizierung')->native(false)->default('client_secret_basic')->selectablePlaceholder(false)
->options(['client_secret_basic' => 'HTTP Basic (client_secret_basic)', 'client_secret_post' => 'Im Formular (client_secret_post)']),
Select::make('config.prompt')->label('Anmeldeaufforderung')->native(false)->placeholder('Anbieter entscheidet')
->options(['login' => 'Immer Passwort abfragen', 'select_account' => 'Konto auswählen lassen']),
Toggle::make('config.use_userinfo')->label('Zusätzliche Angaben vom UserInfo-Endpunkt laden')->default(true)->columnSpanFull(),
];
}
public function secretFields(): array
{
return ['client_secret'];
}
public function defaultAttributeMap(): array
{
return ['first_name' => 'given_name', 'last_name' => 'family_name', 'email' => 'email'];
}
public function attributeSuggestions(?IdentityProvider $provider): array
{
return [
'given_name' => 'Vorname', 'family_name' => 'Nachname', 'name' => 'Anzeigename', 'email' => 'E-Mail',
'preferred_username' => 'Benutzername', 'phone_number' => 'Telefon', 'locale' => 'Sprache',
'address.locality' => 'Ort (Adresse)', 'department' => 'Abteilung (eigener Claim)', 'employee_number' => 'Personalnummer (eigener Claim)',
];
}
public function attributeLabel(): string
{
return 'Claim';
}
public function groupValueLabel(): string
{
return 'Gruppe (Wert im Claim)';
}
public function start(IdentityProvider $provider, Request $request): Response
{
$verifier = Str::random(64);
$security = [
'state' => Str::random(40),
'nonce' => Str::random(40),
'code_challenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='),
];
try {
$url = (new OidcClient($provider))->authorizationUrl(IdentityLoginController::callbackUrlFor($provider), $security);
} catch (Throwable $e) {
report($e);
return redirect('/login')->with('identity_error', 'Der Anmeldedienst „'.$provider->name.'“ ist gerade nicht erreichbar. Bitte später erneut versuchen.');
}
$request->session()->put(self::SESSION, ['state' => $security['state'], 'nonce' => $security['nonce'], 'verifier' => $verifier, 'provider' => (string) $provider->id]);
return redirect()->away($url);
}
protected function authenticate(IdentityProvider $provider, Request $request): ExternalUser
{
$session = $request->session()->pull(self::SESSION);
if ($request->filled('error')) {
logger()->notice('OIDC-Anmeldung abgebrochen: '.$request->string('error').' '.$request->string('error_description'));
throw new IdentityException($request->string('error')->toString() === 'access_denied'
? 'Die Anmeldung wurde abgebrochen.'
: 'Der Anmeldedienst 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.');
}
$client = new OidcClient($provider);
$tokens = $client->exchangeCode((string) $request->query('code'), IdentityLoginController::callbackUrlFor($provider), $session['verifier']);
$claims = $client->validateIdToken($tokens['id_token'], $session['nonce']);
$subject = (string) ($claims['sub'] ?? '');
if ($subject === '') {
throw new IdentityException('Der Anmeldedienst hat keine Benutzerkennung übermittelt.');
}
if ($tokens['access_token'] && $provider->setting('use_userinfo', true)) {
try {
$info = $client->userinfo($tokens['access_token']);
// UserInfo darf nur Angaben derselben Person ergänzen (OIDC Core 5.3.2).
if (($info['sub'] ?? null) === $subject) {
$claims = array_merge($info, $claims);
}
} catch (Throwable $e) {
logger()->warning('OIDC-UserInfo nicht abrufbar: '.$e->getMessage());
}
}
if (isset($claims['email_verified']) && $claims['email_verified'] === false && ! $provider->setting('trust_unverified_email', false)) {
// Unbestätigte Adressen nie zum Verknüpfen bestehender Konten nutzen.
unset($claims['email']);
}
$claims = array_diff_key($claims, array_flip(['nonce', 'at_hash', 'c_hash', 'sid', 'auth_time', 'iat', 'exp', 'nbf']));
$profile = AttributeProfile::build($provider, $claims, [
'display_name' => 'name',
'first_name' => 'given_name',
'last_name' => 'family_name',
'email' => 'email',
]);
return new ExternalUser(
subject: $subject,
profile: $profile,
groups: AttributeProfile::values($claims, (string) $provider->setting('groups_claim', 'groups')),
attributes: $claims,
);
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Inhaus\Plugins\Oidc;
use App\Identity\IdentityDrivers;
use App\Plugins\Plugin;
class OidcPlugin extends Plugin
{
public function register(): void
{
$this->app->make(IdentityDrivers::class)->add(OidcDriver::TYPE, OidcDriver::class);
}
}

View file

@ -0,0 +1,13 @@
{
"slug": "saml",
"name": "Anmeldung: SAML 2",
"version": "1.0.0",
"description": "Anmeldung über SAML 2, z. B. ADFS, Shibboleth, Okta oder Keycloak – mit Metadaten-Import, Gruppen-Zuordnung und Profil-Übernahme.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Saml\\",
"class": "Inhaus\\Plugins\\Saml\\SamlPlugin",
"requires": {
"core": ">=0.9.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,219 @@
<?php
namespace Inhaus\Plugins\Saml;
use App\Identity\AttributeProfile;
use App\Identity\ExternalUser;
use App\Identity\IdentityDriver;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Icons\Heroicon;
use Illuminate\Http\Request;
use OneLogin\Saml2\Constants;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Anmeldung über SAML 2 (z. B. ADFS, Shibboleth, Okta, Keycloak).
*/
class SamlDriver extends IdentityDriver
{
public const TYPE = 'saml';
/** Übliche Attributnamen (ADFS/Entra-Claims und LDAP-OIDs). */
private const CLAIMS = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/';
public function __construct(private readonly SamlService $saml) {}
public function type(): string
{
return self::TYPE;
}
public function label(): string
{
return 'SAML 2';
}
public function description(): string
{
return 'ADFS, Shibboleth, Okta, Keycloak und andere SAML-Anbieter.';
}
public function connectionHelp(?IdentityProvider $provider): string
{
if (! $provider) {
return 'Nach dem ersten Speichern stehen hier die Metadaten-Adresse und die Antwort-URL (ACS) für den Anbieter.';
}
return 'Beim Anbieter eintragen – am einfachsten über die Metadaten: <code>'.e(route('identity.metadata', $provider)).'</code><br>'
.'Oder von Hand: Entity-ID <code>'.e($this->saml->entityId($provider)).'</code>, Antwort-URL (ACS, HTTP-POST) <code>'.e($this->saml->acsUrl($provider)).'</code>. '
.'Die Assertion muss signiert sein (SHA-256).';
}
public function connectionSchema(): array
{
return [
TextInput::make('config.metadata_url')->label('Metadaten-Adresse des Anbieters')->url()->maxLength(500)->columnSpanFull()
->placeholder('https://adfs.firma.de/FederationMetadata/2007-06/FederationMetadata.xml')
->helperText('Optional: Mit „Metadaten laden“ werden die Felder darunter ausgefüllt.'),
TextInput::make('config.idp_entity_id')->label('Entity-ID des Anbieters')->required()->maxLength(500),
TextInput::make('config.idp_sso_url')->label('Anmeldeadresse (SSO, HTTP-Redirect)')->required()->url()->maxLength(500),
Textarea::make('config.idp_certificates')->label('Signaturzertifikat(e) des Anbieters')->required()->rows(5)->columnSpanFull()
->helperText('PEM-Format. Beim Zertifikatswechsel altes und neues untereinander eintragen.')
->rule(fn () => function (string $attribute, $value, $fail) {
foreach (SamlService::certificates($value) as $cert) {
if (! @openssl_x509_read(SamlService::pem($cert))) {
$fail('Mindestens ein Zertifikat ist nicht lesbar.');
return;
}
}
if (SamlService::certificates($value) === []) {
$fail('Bitte ein Zertifikat eintragen.');
}
}),
Select::make('config.name_id_format')->label('NameID-Format')->native(false)->options(SamlService::NAME_ID_FORMATS)
->default(Constants::NAMEID_UNSPECIFIED)->selectablePlaceholder(false),
TextInput::make('config.subject_attribute')->label('Attribut mit der dauerhaften Kennung')->maxLength(500)
->placeholder('leer = NameID')
->helperText('z. B. objectGUID oder ImmutableID, falls die NameID eine E-Mail-Adresse ist, die sich ändern kann.'),
TextInput::make('config.groups_attribute')->label('Attribut mit den Gruppen')->maxLength(500)->columnSpanFull()
->default('http://schemas.microsoft.com/ws/2008/06/identity/claims/groups'),
];
}
public function adminActions(): array
{
return [
Action::make('importSamlMetadata')->label('Metadaten laden')->icon(Heroicon::OutlinedArrowDownTray)->color('gray')->size('sm')
->action(function ($livewire, Set $set) {
$url = (string) data_get($livewire->data, 'config.metadata_url');
if ($url === '') {
Notification::make()->warning()->title('Bitte zuerst die Metadaten-Adresse eintragen')->send();
return;
}
try {
$values = $this->saml->importMetadata($url);
} catch (Throwable $e) {
Notification::make()->danger()->title('Metadaten konnten nicht geladen werden')->body($e->getMessage())->send();
return;
}
foreach ($values as $key => $value) {
$set('config.'.$key, $value);
}
Notification::make()->success()->title('Metadaten übernommen')->body('Bitte prüfen und speichern.')->send();
}),
];
}
public function defaultAttributeMap(): array
{
return [
'first_name' => self::CLAIMS.'givenname',
'last_name' => self::CLAIMS.'surname',
'email' => self::CLAIMS.'emailaddress',
];
}
public function attributeSuggestions(?IdentityProvider $provider): array
{
return [
self::CLAIMS.'givenname' => 'Vorname (ADFS/Entra)',
self::CLAIMS.'surname' => 'Nachname (ADFS/Entra)',
self::CLAIMS.'emailaddress' => 'E-Mail (ADFS/Entra)',
self::CLAIMS.'name' => 'Name (ADFS/Entra)',
'http://schemas.xmlsoap.org/claims/Department' => 'Abteilung (ADFS)',
'urn:oid:2.5.4.42' => 'Vorname (givenName)',
'urn:oid:2.5.4.4' => 'Nachname (sn)',
'urn:oid:0.9.2342.19200300.100.1.3' => 'E-Mail (mail)',
'urn:oid:2.16.840.1.113730.3.1.241' => 'Anzeigename (displayName)',
'urn:oid:2.5.4.12' => 'Funktion (title)',
'urn:oid:2.5.4.11' => 'Abteilung (ou)',
'urn:oid:2.5.4.20' => 'Telefon (telephoneNumber)',
'urn:oid:2.16.840.1.113730.3.1.3' => 'Personalnummer (employeeNumber)',
];
}
public function groupValueLabel(): string
{
return 'Gruppe (Wert im Attribut)';
}
public function start(IdentityProvider $provider, Request $request): Response
{
$intended = (string) $request->session()->get('url.intended', '');
$path = $intended !== '' ? (parse_url($intended, PHP_URL_PATH) ?: '/').(($q = parse_url($intended, PHP_URL_QUERY)) ? '?'.$q : '') : null;
try {
return redirect()->away($this->saml->loginUrl($provider, $path));
} catch (Throwable $e) {
report($e);
return redirect('/login')->with('identity_error', 'Die Anmeldung über „'.$provider->name.'“ ist nicht richtig eingerichtet. Bitte wenden Sie sich an die Administration.');
}
}
protected function authenticate(IdentityProvider $provider, Request $request): ExternalUser
{
if (! $request->isMethod('post') || ! is_string($request->input('SAMLResponse'))) {
throw new IdentityException('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.');
}
$result = $this->saml->consume($provider, $request->input('SAMLResponse'));
$attributes = $result['attributes'];
$subjectAttribute = trim((string) $provider->setting('subject_attribute'));
$subject = $subjectAttribute !== '' ? AttributeProfile::value($attributes, $subjectAttribute) : $result['name_id'];
if ($subjectAttribute === '' && $result['name_id_format'] === Constants::NAMEID_TRANSIENT) {
throw new IdentityException('Der Anmeldedienst liefert nur eine vorübergehende Kennung. Bitte in der Administration ein Attribut mit dauerhafter Kennung festlegen.');
}
if ($subject === null || $subject === '') {
throw new IdentityException('Der Anmeldedienst hat keine Benutzerkennung übermittelt.');
}
$attributes['NameID'] = [$result['name_id']];
$emailFallback = $result['name_id_format'] === Constants::NAMEID_EMAIL_ADDRESS ? 'NameID' : self::CLAIMS.'emailaddress';
$profile = AttributeProfile::build($provider, $attributes, [
'display_name' => self::CLAIMS.'name',
'first_name' => self::CLAIMS.'givenname',
'last_name' => self::CLAIMS.'surname',
'email' => $emailFallback,
]);
return new ExternalUser(
subject: $subject,
profile: $profile,
groups: AttributeProfile::values($attributes, (string) $provider->setting('groups_attribute')),
attributes: $attributes,
);
}
public function intendedUrl(IdentityProvider $provider, Request $request): ?string
{
$relay = (string) $request->input('RelayState', '');
// Nur Pfade im Portal – nie fremde Adressen (offene Weiterleitung).
return str_starts_with($relay, '/') && ! str_starts_with($relay, '//') && ! str_contains($relay, '\\') ? $relay : null;
}
public function metadata(IdentityProvider $provider): ?Response
{
return response($this->saml->metadataXml($provider), 200, ['Content-Type' => 'application/samlmetadata+xml']);
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Inhaus\Plugins\Saml;
use App\Identity\IdentityDrivers;
use App\Plugins\Plugin;
class SamlPlugin extends Plugin
{
public function register(): void
{
$this->app->make(IdentityDrivers::class)->add(SamlDriver::TYPE, SamlDriver::class);
}
}

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;
}
}
}