Anmeldung mit Microsoft Entra ID
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m37s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m41s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m40s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m42s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m10s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m6s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m55s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m2s
CI / Build-Artefakte aktuell (pull_request) Successful in 52s

- OpenID Connect mit PKCE, State und Nonce; ID-Token-Prüfung gegen die
  Microsoft-Schlüssel (Signatur, Mandant, App, Gültigkeit, Nonce) inkl.
  Neuladen bei Schlüsselwechsel
- Konto bei erster Anmeldung anlegen oder per E-Mail verknüpfen, optionale
  Domain-Beschränkung, deaktivierte Konten bleiben gesperrt
- Gruppen (inkl. Overage über Graph, transitiv) und App-Rollen → Rollen,
  additiv; nur Zuweisungen aus Entra werden abgeglichen, manuelle bleiben
- Profilfelder, Vorgesetzte*r und Profilfoto aus Graph, je Feld wählbar und
  im Portal schreibgeschützt; Fallback auf Token-Angaben, wenn Graph ausfällt
- Hintergrund-Abgleich mit Delta-Abfragen (Zeitbudget, Fortsetzung über
  nextLink/deltaLink), Offboarding deaktivierter/gelöschter Konten, optionale
  Vorab-Anlage, Fotos/Vorgesetzte rollierend, Gruppen und App-Rollen stündlich
- Admin „Anmeldung“: Einrichtung mit Umleitungs-URI und Berechtigungen,
  verschlüsseltes Geheimnis (nie im Browser), Gruppensuche, Status, „Mapping testen“
- Fix: @odata.nextLink/@odata.deltaLink wurden als Pfad gelesen – Folgeseiten fehlten
- Profilseite mit Vorgesetzter/m und Mitarbeitenden; Version 0.4.0

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 07:52:22 +00:00
parent 9ddc35a62c
commit 51c94cd0cf
111 changed files with 5721 additions and 244 deletions

View file

@ -0,0 +1,185 @@
<?php
namespace App\Identity\Entra;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
/**
* Zugriff auf Microsoft Entra ID (OpenID Connect) und Microsoft Graph.
*/
class EntraClient
{
public const LOGIN_URL = 'https://login.microsoftonline.com';
public const GRAPH_URL = 'https://graph.microsoft.com/v1.0';
/** Delegierte Berechtigungen bei der Anmeldung. GroupMember.Read.All braucht Admin-Zustimmung. */
public const SCOPES = 'openid profile email offline_access User.Read GroupMember.Read.All';
public function __construct(private readonly IdentityProvider $provider) {}
public function tenant(): string
{
return (string) $this->provider->setting('tenant_id');
}
public function clientId(): string
{
return (string) $this->provider->setting('client_id');
}
public function issuer(): string
{
return self::LOGIN_URL.'/'.$this->tenant().'/v2.0';
}
/**
* @param array{state: string, nonce: string, code_challenge: string} $security
*/
public function authorizationUrl(string $redirectUri, array $security): string
{
return self::LOGIN_URL.'/'.$this->tenant().'/oauth2/v2.0/authorize?'.http_build_query([
'client_id' => $this->clientId(),
'response_type' => 'code',
'redirect_uri' => $redirectUri,
'response_mode' => 'query',
'scope' => self::SCOPES,
'state' => $security['state'],
'nonce' => $security['nonce'],
'code_challenge' => $security['code_challenge'],
'code_challenge_method' => 'S256',
'prompt' => 'select_account',
]);
}
/**
* Autorisierungscode gegen Token tauschen (mit PKCE-Verifier).
*
* @return array{id_token: string, access_token: string}
*/
public function exchangeCode(string $code, string $redirectUri, string $codeVerifier): array
{
$response = $this->tokenRequest([
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $redirectUri,
'code_verifier' => $codeVerifier,
'scope' => self::SCOPES,
]);
if (! is_string($response['id_token'] ?? null) || ! is_string($response['access_token'] ?? null)) {
throw new IdentityException('Microsoft hat keine gültige Anmeldung zurückgegeben.');
}
return ['id_token' => $response['id_token'], 'access_token' => $response['access_token']];
}
/**
* App-Token (Client Credentials) für den Hintergrund-Abgleich – benötigt
* Anwendungsberechtigungen User.Read.All und GroupMember.Read.All.
*/
public function appToken(): string
{
return Cache::remember('entra.app-token.'.$this->provider->id, 3000, fn () => (string) $this->tokenRequest([
'grant_type' => 'client_credentials',
'scope' => 'https://graph.microsoft.com/.default',
])['access_token']);
}
public function forgetAppToken(): void
{
Cache::forget('entra.app-token.'.$this->provider->id);
}
/**
* Öffentliche Signaturschlüssel von Microsoft (gecacht, bei unbekanntem
* Schlüssel einmal neu geladen – Microsoft wechselt sie regelmäßig).
*
* @return array{keys: list<array<string, mixed>>}
*/
public function jwks(bool $refresh = false): array
{
$key = 'entra.jwks.'.$this->tenant();
if ($refresh) {
Cache::forget($key);
}
return Cache::remember($key, 86400, function () {
$response = Http::timeout(10)->acceptJson()->get(self::LOGIN_URL.'/'.$this->tenant().'/discovery/v2.0/keys');
if (! $response->successful() || ! is_array($response->json('keys'))) {
throw new IdentityException('Die Schlüssel von Microsoft konnten nicht geladen werden. Bitte später erneut versuchen.');
}
return ['keys' => $response->json('keys')];
});
}
public function graph(string $token): PendingRequest
{
return Http::timeout(20)->connectTimeout(10)->acceptJson()->withToken($token)->baseUrl(self::GRAPH_URL);
}
/**
* Alle Seiten einer Graph-Abfrage (@odata.nextLink), höchstens $maxPages.
*
* @param array<string, string> $headers
* @return list<array<string, mixed>>
*/
public function graphAll(string $token, string $url, int $maxPages = 50, array $headers = []): array
{
$items = [];
for ($page = 0; $page < $maxPages && $url; $page++) {
$response = $this->graph($token)->withHeaders($headers)->get($url);
$this->assertGraph($response);
$items = array_merge($items, (array) $response->json('value', []));
$url = ($response->json() ?? [])['@odata.nextLink'] ?? null;
}
return $items;
}
public function assertGraph(Response $response): void
{
if ($response->status() === 403) {
throw new IdentityException('Microsoft Graph verweigert den Zugriff. Bitte die API-Berechtigungen der App-Registrierung und die Administratorzustimmung prüfen.');
}
if (! $response->successful()) {
throw new IdentityException('Microsoft Graph antwortet mit einem Fehler (HTTP '.$response->status().').');
}
}
/**
* @param array<string, string> $params
* @return array<string, mixed>
*/
private function tokenRequest(array $params): array
{
$response = Http::asForm()->timeout(15)->acceptJson()->post(self::LOGIN_URL.'/'.$this->tenant().'/oauth2/v2.0/token', [
'client_id' => $this->clientId(),
'client_secret' => (string) $this->provider->setting('client_secret'),
...$params,
]);
if (! $response->successful()) {
$code = (string) $response->json('error');
throw new IdentityException(match (true) {
str_contains((string) $response->json('error_description'), 'AADSTS7000215') => 'Das Client-Secret der App-Registrierung ist ungültig oder abgelaufen.',
$code === 'invalid_grant' => 'Die Anmeldung ist abgelaufen. Bitte erneut versuchen.',
$code === 'unauthorized_client', $code === 'invalid_client' => 'Die App-Registrierung in Entra ID ist nicht korrekt eingerichtet (Client-ID oder Secret).',
default => 'Microsoft hat die Anmeldung abgelehnt ('.($code ?: 'HTTP '.$response->status()).').',
});
}
return (array) $response->json();
}
}

View file

@ -0,0 +1,277 @@
<?php
namespace App\Identity\Entra;
use App\Identity\IdentityException;
use App\Identity\IdentitySync;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\UserIdentity;
use App\Support\Settings;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Hintergrund-Abgleich mit Entra ID – ohne dass sich jemand anmelden muss.
*
* - Benutzer per Delta-Abfrage (/users/delta): nur Änderungen seit dem letzten
* Lauf; deaktivierte oder gelöschte Konten werden im Portal deaktiviert
* (Offboarding). Optional werden neue Konten vorab angelegt.
* - Fotos und Vorgesetzte rollierend in kleinen Portionen.
* - Gruppen- und App-Rollen-Zuordnungen stündlich für alle verknüpften Konten.
*
* Arbeitet mit Zeitbudget und setzt beim nächsten Lauf fort (Shared Hosting,
* Pseudo-Cron). Benötigt Anwendungsberechtigungen User.Read.All und
* GroupMember.Read.All (Administratorzustimmung).
*/
class EntraDirectorySync
{
public const PHOTOS_PER_RUN = 25;
public const GROUP_SYNC_INTERVAL = 3600;
public function __construct(
private readonly IdentitySync $sync,
private readonly Settings $settings,
) {}
public function runAll(int $budgetSeconds = 45): void
{
IdentityProvider::query()->where('enabled', true)->where('type', IdentityProvider::ENTRA)->get()
->filter(fn (IdentityProvider $p) => (bool) $p->setting('directory_sync', false))
->each(fn (IdentityProvider $p) => $this->run($p, $budgetSeconds));
}
public function run(IdentityProvider $provider, int $budgetSeconds = 45): void
{
$deadline = microtime(true) + $budgetSeconds;
$client = new EntraClient($provider);
try {
$token = $client->appToken();
$this->syncUsers($provider, $client, $token, $deadline);
$this->syncPhotosAndManagers($provider, $client, $token, $deadline);
if (now()->getTimestamp() - (int) $this->state($provider, 'groups_synced_at', 0) >= self::GROUP_SYNC_INTERVAL) {
$this->syncGroups($provider, $client, $token);
$this->saveState($provider, ['groups_synced_at' => now()->getTimestamp()]);
}
$this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => null]);
} catch (Throwable $e) {
$client->forgetAppToken();
Log::error("Entra-Abgleich ({$provider->name}) fehlgeschlagen: ".$e->getMessage());
$this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => $e->getMessage()]);
}
}
/**
* @return array<string, mixed>
*/
public function status(IdentityProvider $provider): array
{
return (array) $this->settings->get('identity.'.$provider->id.'.sync', []);
}
private function syncUsers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
{
$url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.EntraProfile::SELECT;
while ($url && microtime(true) < $deadline) {
$response = $client->graph($token)->get($url);
// Abgelaufener Delta-Link: von vorn beginnen.
if ($response->status() === 410) {
$this->saveState($provider, ['delta_link' => null, 'next_link' => null]);
return;
}
$client->assertGraph($response);
foreach ((array) $response->json('value', []) as $graphUser) {
$this->applyUser($provider, (array) $graphUser);
}
if ($next = ($response->json() ?? [])['@odata.nextLink'] ?? null) {
$url = $next;
$this->saveState($provider, ['next_link' => $next]);
} else {
$this->saveState($provider, ['delta_link' => ($response->json() ?? [])['@odata.deltaLink'] ?? null, 'next_link' => null, 'users_synced_at' => now()->getTimestamp()]);
$url = null;
}
}
}
/**
* @param array<string, mixed> $graphUser
*/
private function applyUser(IdentityProvider $provider, array $graphUser): void
{
$subject = (string) ($graphUser['id'] ?? '');
if ($subject === '') {
return;
}
$identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first();
if (isset($graphUser['@removed']) || ($graphUser['accountEnabled'] ?? true) === false) {
if ($identity?->user) {
$this->sync->deactivate($provider, $identity);
}
return;
}
if (! $identity) {
$createAllowed = $provider->setting('directory_create_users', false)
&& ($graphUser['userType'] ?? 'Member') === 'Member'
&& ! empty($graphUser['mail']);
// Ohne Vorab-Anlage: nur bestehende Konten per E-Mail verknüpfen.
try {
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($graphUser), (bool) $createAllowed);
} catch (IdentityException) {
return; // z. B. nicht erlaubte E-Mail-Domain – dieses Konto überspringen
}
if (! $user) {
return;
}
$identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first();
}
// Delta liefert nur geänderte Felder – fehlende Felder nicht leeren.
$profile = array_intersect_key(EntraProfile::fromGraph($graphUser), array_flip(array_map(fn ($key) => match ($key) {
'givenName' => 'first_name', 'surname' => 'last_name', 'mail' => 'email', 'jobTitle' => 'job_title',
'department' => 'department', 'officeLocation' => 'location', 'businessPhones' => 'phone', 'mobilePhone' => 'mobile',
'displayName' => 'display_name', default => '-',
}, array_keys($graphUser))));
$this->sync->syncProfile($provider, $identity->user, $profile);
}
private function syncPhotosAndManagers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void
{
$withPhoto = (bool) $provider->setting('sync_photo', true);
$withManager = in_array('manager', $provider->syncedFields(), true);
if (! $withPhoto && ! $withManager) {
return;
}
$identities = UserIdentity::query()->with('user')
->where('identity_provider_id', $provider->id)
->whereHas('user', fn ($q) => $q->where('is_active', true))
->orderByRaw('synced_at is not null')->orderBy('synced_at')
->limit(self::PHOTOS_PER_RUN)->get();
foreach ($identities as $identity) {
if (microtime(true) >= $deadline) {
return;
}
if ($withPhoto) {
$response = $client->graph($token)->accept('image/*')->get('/users/'.$identity->subject.'/photo/$value');
if ($response->successful() || $response->status() === 404) {
$this->sync->syncPhoto($identity, $response->successful() ? $response->body() : null);
}
}
if ($withManager) {
$manager = $client->graph($token)->get('/users/'.$identity->subject.'/manager', ['$select' => 'id']);
if ($manager->successful() || $manager->status() === 404) {
$this->sync->syncProfile($provider, $identity->user, ['manager_subject' => $manager->successful() ? $manager->json('id') : null]);
}
}
$identity->forceFill(['synced_at' => now()])->save();
}
}
/**
* Gruppen- und App-Rollen-Zuordnungen für alle verknüpften Konten neu berechnen.
*/
private function syncGroups(IdentityProvider $provider, EntraClient $client, string $token): void
{
$mappings = $provider->mappings()->get();
$groupsBySubject = [];
$appRolesBySubject = [];
foreach ($mappings->where('kind', IdpGroupMapping::GROUP)->pluck('external_id')->unique() as $groupId) {
foreach ($this->transitiveUserIds($client, $token, $groupId) as $subject) {
$groupsBySubject[$subject][] = $groupId;
}
}
if ($mappings->where('kind', IdpGroupMapping::APP_ROLE)->isNotEmpty()) {
$appRolesBySubject = $this->appRoleAssignments($provider, $client, $token);
}
UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)
->whereHas('user', fn ($q) => $q->where('is_active', true))
->each(fn (UserIdentity $identity) => $this->sync->syncRoles(
$provider,
$identity->user,
$groupsBySubject[$identity->subject] ?? [],
array_values(array_unique($appRolesBySubject[$identity->subject] ?? [])),
));
}
/**
* @return list<string>
*/
private function transitiveUserIds(EntraClient $client, string $token, string $groupId): array
{
return array_column($client->graphAll($token, '/groups/'.$groupId.'/transitiveMembers/microsoft.graph.user?$select=id&$top=999'), 'id');
}
/**
* App-Rollen der App-Registrierung: direkt zugewiesene Personen und Gruppen (aufgelöst).
*
* @return array<string, list<string>> Objekt-ID => Rollen-Werte
*/
private function appRoleAssignments(IdentityProvider $provider, EntraClient $client, string $token): array
{
$servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']);
$client->assertGraph($servicePrincipal);
$values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id')->all();
$result = [];
foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) {
$value = $values[$assignment['appRoleId'] ?? ''] ?? null;
if (! $value) {
continue;
}
$subjects = ($assignment['principalType'] ?? '') === 'Group'
? $this->transitiveUserIds($client, $token, $assignment['principalId'])
: [$assignment['principalId']];
foreach ($subjects as $subject) {
$result[$subject][] = $value;
}
}
return $result;
}
private function state(IdentityProvider $provider, string $key, mixed $default = null): mixed
{
return $this->status($provider)[$key] ?? $default;
}
/**
* @param array<string, mixed> $values
*/
private function saveState(IdentityProvider $provider, array $values): void
{
$this->settings->set('identity.'.$provider->id.'.sync', array_merge($this->status($provider), $values));
}
}

View file

@ -0,0 +1,131 @@
<?php
namespace App\Identity\Entra;
use App\Identity\IdentityException;
use App\Identity\IdentitySync;
use App\Models\IdentityProvider;
use App\Models\User;
use App\Models\UserIdentity;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;
/**
* Anmeldung über Entra ID (OpenID Connect, Autorisierungscode mit PKCE).
*/
class EntraLogin
{
public function __construct(private readonly IdentitySync $sync) {}
/**
* @return array{url: string, session: array<string, string>}
*/
public function start(IdentityProvider $provider, string $redirectUri): array
{
$verifier = Str::random(64);
$security = [
'state' => Str::random(40),
'nonce' => Str::random(40),
'code_challenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='),
];
return [
'url' => (new EntraClient($provider))->authorizationUrl($redirectUri, $security),
'session' => ['state' => $security['state'], 'nonce' => $security['nonce'], 'verifier' => $verifier, 'provider' => (string) $provider->id],
];
}
/**
* @param array<string, string> $session aus start()
*/
public function complete(IdentityProvider $provider, string $code, string $redirectUri, array $session): User
{
$client = new EntraClient($provider);
$tokens = $client->exchangeCode($code, $redirectUri, $session['verifier']);
$claims = (new IdTokenValidator($client))->validate($tokens['id_token'], $session['nonce']);
$subject = (string) $claims['oid'];
[$profile, $groupIds, $photo] = $this->fetchFromGraph($client, $provider, $tokens['access_token'], $claims);
$user = $this->sync->resolveUser($provider, $subject, $profile, (bool) $provider->setting('auto_provision', true));
if (! $user) {
throw new IdentityException('Für Ihr Microsoft-Konto 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', $subject)->firstOrFail();
$identity->update(['last_login_at' => now(), 'email' => $profile['email'] ?? $identity->email]);
$this->sync->syncProfile($provider, $user, $profile);
$this->sync->syncRoles($provider, $user, $groupIds, array_values(array_filter((array) ($claims['roles'] ?? []), 'is_string')));
if ($provider->setting('sync_photo', true) && $photo !== false) {
$this->sync->syncPhoto($identity->fresh('user'), $photo);
}
return $user->fresh();
}
/**
* Profil, Gruppen und Foto über Graph (mit dem Token der angemeldeten Person).
* Fällt Graph aus, reichen die Angaben aus dem ID-Token für die Anmeldung.
*
* @param array<string, mixed> $claims
* @return array{0: array<string, mixed>, 1: list<string>, 2: string|null|false} false = Foto unbekannt
*/
private function fetchFromGraph(EntraClient $client, IdentityProvider $provider, string $token, array $claims): array
{
$groups = array_values(array_filter((array) ($claims['groups'] ?? []), 'is_string'));
$overage = isset($claims['_claim_names']['groups']) || ($claims['hasgroups'] ?? false);
try {
$me = $client->graph($token)->get('/me', ['$select' => EntraProfile::SELECT]);
$client->assertGraph($me);
$withManager = in_array('manager', $provider->syncedFields(), true);
$managerSubject = null;
if ($withManager) {
$manager = $client->graph($token)->get('/me/manager', ['$select' => 'id']);
$managerSubject = $manager->successful() ? $manager->json('id') : null;
}
$profile = EntraProfile::fromGraph((array) $me->json(), $managerSubject, $withManager);
} catch (Throwable $e) {
Log::warning('Entra-Anmeldung: Profil aus Graph nicht abrufbar, nutze ID-Token. '.$e->getMessage());
$profile = EntraProfile::fromClaims($claims);
}
// Group-Overage: Bei vielen Gruppen stehen sie nicht im Token – dann über Graph
// (transitiv, also inklusive verschachtelter Gruppen).
if ($overage || $groups === []) {
try {
$groups = array_column($client->graphAll($token, '/me/transitiveMemberOf/microsoft.graph.group?$select=id&$top=999'), 'id');
} catch (Throwable $e) {
if ($overage) {
Log::error('Entra-Anmeldung: Gruppen konnten nicht ermittelt werden. '.$e->getMessage());
throw new IdentityException('Ihre Gruppenmitgliedschaften konnten nicht ermittelt werden. Bitte später erneut versuchen.');
}
}
}
$photo = false;
if ($provider->setting('sync_photo', true)) {
try {
$response = $client->graph($token)->accept('image/*')->get('/me/photo/$value');
$photo = $response->successful() ? $response->body() : ($response->status() === 404 ? null : false);
} catch (Throwable) {
$photo = false;
}
}
return [$profile, $groups, $photo];
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace App\Identity\Entra;
/**
* Normalisiert Entra-/Graph-Benutzerdaten auf die Profilfelder des Portals.
*/
final class EntraProfile
{
/** Felder, die bei Graph abgefragt werden. */
public const SELECT = 'id,displayName,givenName,surname,mail,userPrincipalName,jobTitle,department,officeLocation,businessPhones,mobilePhone,accountEnabled,userType';
/**
* @param array<string, mixed> $graphUser Antwort von /me bzw. /users/{id}
* @return array<string, mixed>
*/
public static function fromGraph(array $graphUser, ?string $managerSubject = null, bool $withManager = false): array
{
$profile = [
'display_name' => $graphUser['displayName'] ?? null,
'first_name' => $graphUser['givenName'] ?? null,
'last_name' => $graphUser['surname'] ?? null,
'email' => $graphUser['mail'] ?? (str_contains((string) ($graphUser['userPrincipalName'] ?? ''), '#EXT#') ? null : ($graphUser['userPrincipalName'] ?? null)),
'job_title' => $graphUser['jobTitle'] ?? null,
'department' => $graphUser['department'] ?? null,
'location' => $graphUser['officeLocation'] ?? null,
'phone' => $graphUser['businessPhones'][0] ?? null,
'mobile' => $graphUser['mobilePhone'] ?? null,
];
if ($withManager) {
$profile['manager_subject'] = $managerSubject;
}
return $profile;
}
/**
* Rückfall, wenn Graph nicht erreichbar ist: Angaben aus dem ID-Token.
*
* @param array<string, mixed> $claims
* @return array<string, mixed>
*/
public static function fromClaims(array $claims): array
{
return [
'display_name' => $claims['name'] ?? null,
'first_name' => $claims['given_name'] ?? null,
'last_name' => $claims['family_name'] ?? null,
'email' => $claims['email'] ?? $claims['preferred_username'] ?? null,
];
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace App\Identity\Entra;
use App\Identity\IdentityException;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Throwable;
use UnexpectedValueException;
/**
* Prüft das ID-Token von Entra ID: Signatur (Schlüssel von Microsoft), Aussteller
* (genau dieser Mandant), Empfänger (diese App), Gültigkeit und Nonce.
*/
class IdTokenValidator
{
public function __construct(private readonly EntraClient $client) {}
/**
* @return array<string, mixed> Claims
*/
public function validate(string $idToken, string $expectedNonce): array
{
JWT::$leeway = 120;
try {
$claims = $this->decode($idToken, $this->client->jwks());
} catch (UnexpectedValueException $e) {
if (! str_contains($e->getMessage(), '"kid"')) {
throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e);
}
// Unbekannter Schlüssel: Microsoft hat die Schlüssel gewechselt – einmal neu laden.
try {
$claims = $this->decode($idToken, $this->client->jwks(refresh: true));
} catch (UnexpectedValueException $e) {
throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e);
}
}
if (($claims['iss'] ?? null) !== $this->client->issuer()) {
throw new IdentityException('Die Anmeldung stammt nicht aus dem erwarteten Microsoft-Mandanten.');
}
if (($claims['aud'] ?? null) !== $this->client->clientId()) {
throw new IdentityException('Die Anmeldung war für eine andere Anwendung bestimmt.');
}
if (! hash_equals($expectedNonce, (string) ($claims['nonce'] ?? ''))) {
throw new IdentityException('Die Anmeldung konnte nicht zugeordnet werden. Bitte erneut versuchen.');
}
if (! is_string($claims['oid'] ?? null) || $claims['oid'] === '') {
throw new IdentityException('Microsoft hat keine Benutzerkennung übermittelt.');
}
return $claims;
}
/**
* @param array{keys: list<array<string, mixed>>} $jwks
* @return array<string, mixed>
*/
private function decode(string $token, array $jwks): array
{
try {
return (array) json_decode(json_encode(JWT::decode($token, JWK::parseKeySet($jwks, 'RS256'))), true);
} catch (UnexpectedValueException $e) {
throw $e;
} catch (Throwable $e) {
throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e);
}
}
}

View file

@ -0,0 +1,100 @@
<?php
namespace App\Identity\Entra;
use App\Identity\IdentityException;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\Role;
/**
* „Mapping testen“: Welche Gruppen und App-Rollen liefert Entra für eine Person,
* und welche Rollen entstehen daraus im Portal?
*/
class MappingTester
{
/**
* @return array{user: array<string, mixed>, groups: list<array{id: string, name: string, roles: list<string>}>, app_roles: list<array{value: string, roles: list<string>}>, roles: list<string>}
*/
public function test(IdentityProvider $provider, string $userPrincipal): array
{
$client = new EntraClient($provider);
$token = $client->appToken();
$user = $client->graph($token)->get('/users/'.rawurlencode($userPrincipal), ['$select' => 'id,displayName,mail,userPrincipalName,accountEnabled']);
if ($user->status() === 404) {
throw new IdentityException('Diese Person gibt es in Entra ID nicht.');
}
$client->assertGraph($user);
$id = (string) $user->json('id');
$groups = $client->graphAll($token, '/users/'.$id.'/transitiveMemberOf/microsoft.graph.group?$select=id,displayName&$top=999');
$servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']);
$appRoles = [];
if ($servicePrincipal->successful()) {
$values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id');
$assignments = $client->graphAll($token, '/users/'.$id.'/appRoleAssignments?$top=999');
$groupIds = array_column($groups, 'id');
foreach ($assignments as $assignment) {
if (($assignment['resourceId'] ?? null) === $servicePrincipal->json('id') && $values->has($assignment['appRoleId'] ?? '')) {
$appRoles[] = $values[$assignment['appRoleId']];
}
}
// Über Gruppen zugewiesene App-Rollen
foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) {
if (($assignment['principalType'] ?? '') === 'Group' && in_array($assignment['principalId'], $groupIds, true) && $values->has($assignment['appRoleId'] ?? '')) {
$appRoles[] = $values[$assignment['appRoleId']];
}
}
}
$mappings = $provider->mappings()->with('role')->get();
$roleNames = fn (string $kind, string $external) => $mappings
->filter(fn (IdpGroupMapping $m) => $m->kind === $kind && strtolower($m->external_id) === strtolower($external))
->map(fn (IdpGroupMapping $m) => $m->role->name)->values()->all();
$groupRows = array_map(fn (array $g) => ['id' => $g['id'], 'name' => $g['displayName'] ?? $g['id'], 'roles' => $roleNames(IdpGroupMapping::GROUP, $g['id'])], $groups);
usort($groupRows, fn ($a, $b) => [empty($a['roles']), $a['name']] <=> [empty($b['roles']), $b['name']]);
$appRoleRows = array_map(fn (string $v) => ['value' => $v, 'roles' => $roleNames(IdpGroupMapping::APP_ROLE, $v)], array_values(array_unique($appRoles)));
$roles = collect($groupRows)->pluck('roles')->flatten()->merge(collect($appRoleRows)->pluck('roles')->flatten());
if ($default = $provider->setting('default_role_id')) {
$roles->push(Role::query()->find($default)?->name.' (Standardrolle)');
}
return [
'user' => [
'name' => $user->json('displayName'),
'email' => $user->json('mail') ?: $user->json('userPrincipalName'),
'enabled' => (bool) $user->json('accountEnabled', true),
],
'groups' => $groupRows,
'app_roles' => $appRoleRows,
'roles' => $roles->filter()->unique()->values()->all(),
];
}
/**
* Gruppensuche für das Mapping-Formular.
*
* @return array<string, string> Objekt-ID => Anzeigename
*/
public function searchGroups(IdentityProvider $provider, string $search): array
{
$client = new EntraClient($provider);
$response = $client->graph($client->appToken())
->withHeaders(['ConsistencyLevel' => 'eventual'])
->get('/groups', ['$search' => '"displayName:'.str_replace('"', '', $search).'"', '$select' => 'id,displayName', '$top' => 20]);
$client->assertGraph($response);
return collect((array) $response->json('value', []))->mapWithKeys(fn ($g) => [$g['id'] => $g['displayName'].' ('.substr($g['id'], 0, 8).'…)'])->all();
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace App\Identity;
use RuntimeException;
/**
* Anmeldung über einen Identity Provider ist fehlgeschlagen. Die Meldung ist
* für die anmeldende Person gedacht (deutsch, ohne technische Details).
*/
class IdentityException extends RuntimeException {}

View file

@ -0,0 +1,223 @@
<?php
namespace App\Identity;
use App\Models\IdentityProvider;
use App\Models\IdpGroupMapping;
use App\Models\User;
use App\Models\UserIdentity;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Permissions\Permissions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;
/**
* Überträgt Daten eines Identity Providers ins Portal: Konto finden oder anlegen,
* Profilfelder, Foto und Rollen. Wird bei der Anmeldung und im Hintergrund-Abgleich genutzt.
*/
class IdentitySync
{
public function __construct(private readonly Avatars $avatars) {}
/**
* Konto zu einer externen Identität finden, verknüpfen oder anlegen.
*
* @param array<string, mixed> $profile normalisiertes Profil (siehe EntraProfile)
*/
public function resolveUser(IdentityProvider $provider, string $subject, array $profile, bool $allowCreate): ?User
{
$identity = UserIdentity::query()->with('user')
->where('identity_provider_id', $provider->id)->where('subject', $subject)->first();
if ($identity?->user) {
return $identity->user;
}
$email = isset($profile['email']) ? Str::lower((string) $profile['email']) : null;
if ($email && ! $provider->isEmailDomainAllowed($email)) {
throw new IdentityException('Konten mit dieser E-Mail-Domain dürfen sich hier nicht anmelden.');
}
$user = $email && $provider->setting('link_by_email', true)
? User::query()->where('email', $email)->first()
: null;
if (! $user) {
if (! $allowCreate) {
return null;
}
if (! $email) {
throw new IdentityException('Für dieses Microsoft-Konto ist keine E-Mail-Adresse hinterlegt.');
}
$user = User::query()->create([
'email' => $email,
'first_name' => $profile['first_name'] ?? null,
'last_name' => $profile['last_name'] ?? null,
'name' => $profile['display_name'] ?? $email,
'password' => null,
'is_active' => true,
]);
Audit::log('identity.user_created', ['provider' => $provider->name, 'email' => $email], null);
}
UserIdentity::query()->create([
'user_id' => $user->id,
'identity_provider_id' => $provider->id,
'subject' => $subject,
'email' => $email,
]);
return $user;
}
/**
* Profilfelder übernehmen – nur die in der Konfiguration gewählten.
*
* @param array<string, mixed> $profile
*/
public function syncProfile(IdentityProvider $provider, User $user, array $profile): void
{
$fields = $provider->syncedFields();
$changes = [];
foreach (['first_name', 'last_name', 'job_title', 'department', 'location', 'phone', 'mobile'] as $field) {
if (in_array($field, $fields, true) && array_key_exists($field, $profile)) {
$changes[$field] = $profile[$field] !== '' ? $profile[$field] : null;
}
}
if (in_array('first_name', $fields, true) && empty($profile['first_name']) && empty($profile['last_name']) && ! empty($profile['display_name'])) {
$changes['name'] = $profile['display_name'];
}
if (in_array('email', $fields, true) && ! empty($profile['email'])) {
$email = Str::lower($profile['email']);
if (User::query()->where('email', $email)->whereKeyNot($user->id)->exists()) {
Log::warning("Entra-Abgleich: E-Mail {$email} ist bereits einem anderen Konto zugeordnet – nicht übernommen.");
} else {
$changes['email'] = $email;
}
}
if (in_array('manager', $fields, true) && array_key_exists('manager_subject', $profile)) {
$changes['manager_id'] = $profile['manager_subject']
? UserIdentity::query()->where('identity_provider_id', $provider->id)->where('subject', $profile['manager_subject'])->value('user_id')
: null;
}
if ($changes !== []) {
$user->forceFill($changes)->save();
}
}
/**
* Profilfoto übernehmen, wenn es sich geändert hat. null = kein Foto beim Anbieter.
*/
public function syncPhoto(UserIdentity $identity, ?string $binary): void
{
$user = $identity->user;
try {
if ($binary === null) {
// Nur ein Foto entfernen, das auch aus Entra stammte.
if ($identity->photo_hash !== null) {
$this->avatars->delete($user);
$identity->update(['photo_hash' => null]);
}
return;
}
$hash = hash('sha256', $binary);
if ($hash !== $identity->photo_hash || $user->avatar_path === null) {
$this->avatars->storeFromBinary($user, $binary);
$identity->update(['photo_hash' => $hash]);
}
} catch (Throwable $e) {
Log::warning("Profilfoto für {$user->email} konnte nicht übernommen werden: ".$e->getMessage());
}
}
/**
* Rollen aus Gruppen und App-Rollen abgleichen. Nur Zuweisungen dieses
* Anbieters werden hinzugefügt oder entfernt – manuelle bleiben unberührt.
*
* @param list<string> $groupIds Objekt-IDs der Gruppen
* @param list<string> $appRoles Werte der App-Rollen
* @return list<int> resultierende Rollen-IDs aus diesem Anbieter
*/
public function syncRoles(IdentityProvider $provider, User $user, array $groupIds, array $appRoles): array
{
$desired = [];
foreach ($provider->mappings()->get() as $mapping) {
$values = $mapping->kind === IdpGroupMapping::APP_ROLE ? $appRoles : array_map('strtolower', $groupIds);
$external = $mapping->kind === IdpGroupMapping::APP_ROLE ? $mapping->external_id : strtolower($mapping->external_id);
if (in_array($external, $values, true)) {
$desired[$mapping->role_id.'|'.$provider->sourcePrefix().$mapping->kind.':'.$mapping->external_id] = $mapping->role_id;
}
}
if ($defaultRole = $provider->setting('default_role_id')) {
$desired[$defaultRole.'|'.$provider->sourcePrefix().'default'] = (int) $defaultRole;
}
$current = DB::table('role_user')
->where('user_id', $user->id)
->where('source', 'idp')
->where('source_ref', 'like', $provider->sourcePrefix().'%')
->get(['id', 'role_id', 'source_ref'])
->keyBy(fn ($row) => $row->role_id.'|'.$row->source_ref);
$removed = $current->keys()->diff(array_keys($desired));
$added = collect(array_keys($desired))->diff($current->keys());
if ($removed->isNotEmpty()) {
DB::table('role_user')->whereIn('id', $removed->map(fn ($key) => $current[$key]->id)->all())->delete();
}
foreach ($added as $key) {
[$roleId, $sourceRef] = explode('|', $key, 2);
DB::table('role_user')->insert(['role_id' => (int) $roleId, 'user_id' => $user->id, 'source' => 'idp', 'source_ref' => $sourceRef, 'created_at' => now()]);
}
if ($removed->isNotEmpty() || $added->isNotEmpty()) {
Permissions::flush();
Audit::log('identity.roles_synced', [
'provider' => $provider->name,
'user' => $user->email,
'added' => $added->values()->all(),
'removed' => $removed->values()->all(),
], null);
}
return array_values(array_unique($desired));
}
/**
* Konto wurde beim Anbieter deaktiviert oder gelöscht: im Portal deaktivieren
* und die Rollen aus diesem Anbieter entfernen.
*/
public function deactivate(IdentityProvider $provider, UserIdentity $identity): void
{
$user = $identity->user;
if ($user->is_active) {
$user->forceFill(['is_active' => false])->save();
Audit::log('identity.user_deactivated', ['provider' => $provider->name, 'email' => $user->email], null);
}
$this->syncRoles($provider, $user, [], []);
DB::table('sessions')->where('user_id', $user->id)->delete();
}
}