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>} */ 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 $headers * @return list> */ 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 $params * @return array */ 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(); } }