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
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:
parent
0ab0838050
commit
4fcc41ed30
172 changed files with 18940 additions and 293 deletions
236
plugins-core/oidc/src/OidcClient.php
Normal file
236
plugins-core/oidc/src/OidcClient.php
Normal 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();
|
||||
}
|
||||
}
|
||||
182
plugins-core/oidc/src/OidcDriver.php
Normal file
182
plugins-core/oidc/src/OidcDriver.php
Normal 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
14
plugins-core/oidc/src/OidcPlugin.php
Normal file
14
plugins-core/oidc/src/OidcPlugin.php
Normal 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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue