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