Beliebige Entra-Attribute ins Profil übernehmen; eigene Profilfelder
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m43s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m52s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m49s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m12s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 1m57s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 1m59s
CI / Build-Artefakte aktuell (pull_request) Successful in 57s

- Profilfelder frei definierbar (Typ, Sichtbarkeit, selbst pflegbar), Werte als JSON am Benutzer
- Attribut-Zuordnung je Anbieter statt fester Feldliste: jedes Graph-Attribut inkl.
  verschachtelter Pfade, onPremisesExtensionAttributes und Verzeichniserweiterungen
- Erweiterungsattribute per Knopf aus Entra laden
- $select dynamisch aus der Zuordnung; Delta-Abgleich startet bei geänderter Zuordnung neu
- Rückfall auf Grundattribute, wenn einzelne Attribute nicht lesbar sind
- Ältere Konfiguration (synced_fields) wird weiter gelesen

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 08:09:57 +00:00
parent 51c94cd0cf
commit 6269d3302c
79 changed files with 1442 additions and 273 deletions

View file

@ -0,0 +1,141 @@
<?php
namespace App\Identity\Entra;
use App\Models\IdentityProvider;
use Illuminate\Support\Arr;
/**
* Graph-Benutzerattribute: Vorschlagsliste, Standardzuordnung, $select-Aufbau
* und das Auslesen verschachtelter Werte.
*
* Ein Attribut ist ein Pfad in der Graph-Antwort, z. B. „jobTitle“,
* „employeeOrgData.costCenter“, „onPremisesExtensionAttributes.extensionAttribute3“,
* „businessPhones.0“ oder „extension_<appId>_personalnummer“.
*/
final class EntraAttributes
{
/** Wird immer abgefragt – für Kontoanlage, Verknüpfung und Offboarding. */
public const BASE_SELECT = ['id', 'displayName', 'givenName', 'surname', 'mail', 'userPrincipalName', 'accountEnabled', 'userType'];
/** Standardzuordnung Profilfeld => Attribut (entspricht dem bisherigen Verhalten). */
public const DEFAULT_MAP = [
'first_name' => 'givenName',
'last_name' => 'surname',
'email' => 'mail',
'job_title' => 'jobTitle',
'department' => 'department',
'location' => 'officeLocation',
'phone' => 'businessPhones.0',
'mobile' => 'mobilePhone',
];
/** Häufige Attribute als Vorschläge im Formular. */
public const COMMON = [
'givenName' => 'Vorname',
'surname' => 'Nachname',
'displayName' => 'Anzeigename',
'mail' => 'E-Mail-Adresse',
'userPrincipalName' => 'Benutzerprinzipalname',
'jobTitle' => 'Position',
'department' => 'Abteilung',
'companyName' => 'Firmenname',
'officeLocation' => 'Büro',
'businessPhones.0' => 'Telefon (geschäftlich)',
'mobilePhone' => 'Mobiltelefon',
'faxNumber' => 'Fax',
'streetAddress' => 'Straße',
'postalCode' => 'Postleitzahl',
'city' => 'Ort',
'state' => 'Bundesland',
'country' => 'Land',
'usageLocation' => 'Nutzungsstandort',
'preferredLanguage' => 'Bevorzugte Sprache',
'employeeId' => 'Personalnummer',
'employeeType' => 'Mitarbeitertyp',
'employeeHireDate' => 'Eintrittsdatum',
'employeeLeaveDateTime' => 'Austrittsdatum',
'employeeOrgData.costCenter' => 'Kostenstelle',
'employeeOrgData.division' => 'Bereich',
'otherMails' => 'Weitere E-Mail-Adressen',
'proxyAddresses' => 'Proxyadressen',
'onPremisesSamAccountName' => 'Anmeldename (lokal)',
'onPremisesDistinguishedName' => 'Distinguished Name (lokal)',
'onPremisesExtensionAttributes.extensionAttribute1' => 'Erweiterungsattribut 1 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute2' => 'Erweiterungsattribut 2 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute3' => 'Erweiterungsattribut 3 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute4' => 'Erweiterungsattribut 4 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute5' => 'Erweiterungsattribut 5 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute6' => 'Erweiterungsattribut 6 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute7' => 'Erweiterungsattribut 7 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute8' => 'Erweiterungsattribut 8 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute9' => 'Erweiterungsattribut 9 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute10' => 'Erweiterungsattribut 10 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute11' => 'Erweiterungsattribut 11 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute12' => 'Erweiterungsattribut 12 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute13' => 'Erweiterungsattribut 13 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute14' => 'Erweiterungsattribut 14 (lokal)',
'onPremisesExtensionAttributes.extensionAttribute15' => 'Erweiterungsattribut 15 (lokal)',
];
/** Erlaubte Schreibweise eines Attributpfads. */
public const PATH_PATTERN = '/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$/';
/**
* $select für /me, /users/{id} und /users/delta.
*/
public static function select(IdentityProvider $provider): string
{
$top = array_map(fn (string $path) => self::topLevel($path), array_values($provider->attributeMap()));
return implode(',', array_values(array_unique([...self::BASE_SELECT, ...$top])));
}
public static function topLevel(string $path): string
{
return explode('.', $path, 2)[0];
}
/**
* Wert eines Attributpfads als Text. Listen werden mit Komma verbunden,
* Wahrheitswerte als „Ja“/„Nein“ ausgegeben; leere Werte ergeben null.
*
* @param array<string, mixed> $graphUser
*/
public static function value(array $graphUser, string $path): ?string
{
$value = $graphUser;
foreach (explode('.', $path) as $segment) {
if (! is_array($value) || ! array_key_exists($segment, $value)) {
return null;
}
$value = $value[$segment];
}
if (is_array($value)) {
$value = implode(', ', array_filter(Arr::flatten($value), fn ($v) => is_scalar($v) && $v !== ''));
} elseif (is_bool($value)) {
$value = $value ? 'Ja' : 'Nein';
}
$value = is_scalar($value) ? trim((string) $value) : '';
return $value === '' ? null : $value;
}
/**
* Vorschlagsliste fürs Formular: häufige Attribute plus geladene Verzeichniserweiterungen.
*
* @return array<string, string> Pfad => Beschreibung
*/
public static function suggestions(?IdentityProvider $provider): array
{
$extensions = collect((array) $provider?->setting('extension_properties', []))
->mapWithKeys(fn ($name) => [(string) $name => 'Verzeichniserweiterung'])
->all();
return self::COMMON + $extensions;
}
}

View file

@ -75,7 +75,14 @@ class EntraDirectorySync
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;
$select = EntraAttributes::select($provider);
// Neue Attribute zugeordnet: Der alte Delta-Link liefert sie nicht – einmal komplett abgleichen.
if ($this->state($provider, 'select') !== $select) {
$this->saveState($provider, ['delta_link' => null, 'next_link' => null, 'select' => $select]);
}
$url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.$select;
while ($url && microtime(true) < $deadline) {
$response = $client->graph($token)->get($url);
@ -131,7 +138,7 @@ class EntraDirectorySync
// Ohne Vorab-Anlage: nur bestehende Konten per E-Mail verknüpfen.
try {
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($graphUser), (bool) $createAllowed);
$user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($provider, $graphUser), (bool) $createAllowed);
} catch (IdentityException) {
return; // z. B. nicht erlaubte E-Mail-Domain – dieses Konto überspringen
}
@ -144,11 +151,7 @@ class EntraDirectorySync
}
// 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))));
$profile = EntraProfile::fromGraph($provider, $graphUser, partial: true);
$this->sync->syncProfile($provider, $identity->user, $profile);
}
@ -156,7 +159,7 @@ class EntraDirectorySync
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);
$withManager = $provider->syncsManager();
if (! $withPhoto && ! $withManager) {
return;

View file

@ -84,10 +84,18 @@ class EntraLogin
$overage = isset($claims['_claim_names']['groups']) || ($claims['hasgroups'] ?? false);
try {
$me = $client->graph($token)->get('/me', ['$select' => EntraProfile::SELECT]);
$me = $client->graph($token)->get('/me', ['$select' => EntraAttributes::select($provider)]);
// Einzelne Attribute brauchen weitere Berechtigungen (z. B. employeeHireDate) –
// dann wenigstens die Grundangaben übernehmen.
if ($me->clientError() && $me->status() !== 401) {
Log::warning('Entra-Anmeldung: Zugeordnete Attribute nicht abrufbar ('.$me->status().'), nutze Grundangaben.');
$me = $client->graph($token)->get('/me', ['$select' => implode(',', EntraAttributes::BASE_SELECT)]);
}
$client->assertGraph($me);
$withManager = in_array('manager', $provider->syncedFields(), true);
$withManager = $provider->syncsManager();
$managerSubject = null;
if ($withManager) {
@ -95,7 +103,7 @@ class EntraLogin
$managerSubject = $manager->successful() ? $manager->json('id') : null;
}
$profile = EntraProfile::fromGraph((array) $me->json(), $managerSubject, $withManager);
$profile = EntraProfile::fromGraph($provider, (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);

View file

@ -2,31 +2,57 @@
namespace App\Identity\Entra;
use App\Models\IdentityProvider;
/**
* Normalisiert Entra-/Graph-Benutzerdaten auf die Profilfelder des Portals.
* Normalisiert Entra-/Graph-Benutzerdaten auf die Profilfelder des Portals –
* gemäß der Attribut-Zuordnung des Anbieters.
*
* Ergebnis: display_name, Kernfelder (first_name, email, …), freie Felder unter
* „custom“ und – falls abgefragt – manager_subject.
*/
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}
* @param array<string, mixed> $graphUser Antwort von /me, /users/{id} oder /users/delta
* @param bool $partial Delta-Antwort: nur Felder liefern, deren Attribut enthalten ist
* @return array<string, mixed>
*/
public static function fromGraph(array $graphUser, ?string $managerSubject = null, bool $withManager = false): array
public static function fromGraph(IdentityProvider $provider, array $graphUser, ?string $managerSubject = null, bool $withManager = false, bool $partial = 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,
];
$present = fn (string $path) => ! $partial || array_key_exists(EntraAttributes::topLevel($path), $graphUser);
$profile = [];
if ($present('displayName')) {
$profile['display_name'] = EntraAttributes::value($graphUser, 'displayName');
}
// Grundwerte für Kontoanlage und Verknüpfung; die Zuordnung überschreibt sie.
foreach (['first_name' => 'givenName', 'last_name' => 'surname', 'email' => 'mail'] as $field => $path) {
if ($present($path)) {
$profile[$field] = EntraAttributes::value($graphUser, $path);
}
}
foreach ($provider->attributeMap() as $target => $path) {
if (! $present($path)) {
continue;
}
$value = EntraAttributes::value($graphUser, $path);
if (str_starts_with($target, 'custom.')) {
$profile['custom'][substr($target, 7)] = $value;
} else {
$profile[$target] = $value;
}
}
// Gastkonten haben oft keine „mail“; der UPN ist dann eine #EXT#-Adresse.
if (array_key_exists('email', $profile) && $profile['email'] === null && ! $partial) {
$upn = (string) ($graphUser['userPrincipalName'] ?? '');
$profile['email'] = $upn !== '' && ! str_contains($upn, '#EXT#') ? $upn : null;
}
if ($withManager) {
$profile['manager_subject'] = $managerSubject;

View file

@ -97,4 +97,28 @@ class MappingTester
return collect((array) $response->json('value', []))->mapWithKeys(fn ($g) => [$g['id'] => $g['displayName'].' ('.substr($g['id'], 0, 8).'…)'])->all();
}
/**
* Verzeichniserweiterungen des Mandanten (extension_<appId>_<name>) für Benutzer –
* etwa aus Entra Connect synchronisierte AD-Attribute. Wird in der Konfiguration
* gespeichert und im Formular als Vorschlag angeboten.
*
* @return list<string>
*/
public function loadExtensionProperties(IdentityProvider $provider): array
{
$client = new EntraClient($provider);
$response = $client->graph($client->appToken())->post('/directoryObjects/getAvailableExtensionProperties', (object) []);
$client->assertGraph($response);
$names = collect((array) $response->json('value', []))
->filter(fn ($property) => in_array('User', (array) ($property['targetObjects'] ?? []), true))
->pluck('name')
->filter(fn ($name) => is_string($name) && preg_match(EntraAttributes::PATH_PATTERN, $name))
->unique()->sort()->values()->all();
$provider->update(['config' => array_merge((array) $provider->config, ['extension_properties' => $names])]);
return $names;
}
}

View file

@ -9,6 +9,8 @@ use App\Models\UserIdentity;
use App\Support\Audit;
use App\Support\Avatars;
use App\Support\Permissions\Permissions;
use App\Support\ProfileFields;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@ -20,7 +22,10 @@ use Throwable;
*/
class IdentitySync
{
public function __construct(private readonly Avatars $avatars) {}
public function __construct(
private readonly Avatars $avatars,
private readonly ProfileFields $profileFields,
) {}
/**
* Konto zu einer externen Identität finden, verknüpfen oder anlegen.
@ -113,11 +118,56 @@ class IdentitySync
: null;
}
$custom = $this->customFieldChanges($user, $fields, (array) ($profile['custom'] ?? []));
if ($custom !== null) {
$changes['custom_fields'] = $custom;
}
if ($changes !== []) {
$user->forceFill($changes)->save();
}
}
/**
* Freie Profilfelder aus dem Anbieter übernehmen. Datumswerte werden als
* Y-m-d gespeichert, Werte ohne Felddefinition ignoriert.
*
* @param list<string> $fields
* @param array<string, string|null> $incoming
* @return array<string, string>|null null = keine Änderung
*/
private function customFieldChanges(User $user, array $fields, array $incoming): ?array
{
$definitions = $this->profileFields->all()->keyBy('key');
$values = (array) ($user->custom_fields ?? []);
$before = $values;
foreach ($incoming as $key => $value) {
$field = $definitions->get($key);
if (! $field || ! in_array('custom.'.$key, $fields, true)) {
continue;
}
if ($value !== null && $field->type === 'date') {
try {
$value = Carbon::parse($value)->format('Y-m-d');
} catch (Throwable) {
// Unlesbares Datum: unverändert übernehmen.
}
}
if ($value === null) {
unset($values[$key]);
} else {
$values[$key] = $value;
}
}
return $values === $before ? null : $values;
}
/**
* Profilfoto übernehmen, wenn es sich geändert hat. null = kein Foto beim Anbieter.
*/