using Microsoft.Graph; using Microsoft.Identity.Client; using Microsoft.Kiota.Abstractions.Authentication; namespace SharepointToolbox.Infrastructure.Auth; public class GraphClientFactory { private readonly MsalClientFactory _msalFactory; public GraphClientFactory(MsalClientFactory msalFactory) { _msalFactory = msalFactory; } /// /// Creates a GraphServiceClient that acquires tokens via the same MSAL PCA /// used for SharePoint auth, but with Graph scopes. Uses the /common authority /// and the .default scope (whatever the client is pre-consented for). /// public Task CreateClientAsync(string clientId, CancellationToken ct) => CreateClientAsync(clientId, tenantId: null, scopes: null, ct); /// /// Creates a GraphServiceClient pinned to a specific tenant authority. /// Pass the tenant domain (e.g. "contoso.onmicrosoft.com") or tenant GUID. /// Null falls back to /common. /// public Task CreateClientAsync(string clientId, string? tenantId, CancellationToken ct) => CreateClientAsync(clientId, tenantId, scopes: null, ct); /// /// Creates a GraphServiceClient with explicit Graph delegated scopes. /// Use when .default is insufficient — typically for admin actions that /// need scopes not pre-consented on the bootstrap client (e.g. app registration /// requires Application.ReadWrite.All and /// DelegatedPermissionGrant.ReadWrite.All). Triggers an admin-consent /// prompt on first use if the tenant has not yet consented. /// public async Task CreateClientAsync( string clientId, string? tenantId, string[]? scopes, CancellationToken ct) { var pca = await _msalFactory.GetOrCreateAsync(clientId); // When a tenant is specified we must NOT reuse cached accounts from /common // (or a different tenant) — they route tokens to the wrong authority. IAccount? account = null; if (tenantId is null) { var accounts = await pca.GetAccountsAsync(); account = accounts.FirstOrDefault(); } var graphScopes = scopes ?? new[] { "https://graph.microsoft.com/.default" }; var tokenProvider = new MsalTokenProvider(pca, account, graphScopes, tenantId); var authProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider); return new GraphServiceClient(authProvider); } } /// /// Bridges MSAL PCA token acquisition with Graph SDK's IAccessTokenProvider interface. /// internal class MsalTokenProvider : IAccessTokenProvider { private readonly IPublicClientApplication _pca; private readonly IAccount? _account; private readonly string[] _scopes; private readonly string? _tenantId; public MsalTokenProvider(IPublicClientApplication pca, IAccount? account, string[] scopes, string? tenantId = null) { _pca = pca; _account = account; _scopes = scopes; _tenantId = tenantId; } public AllowedHostsValidator AllowedHostsValidator { get; } = new(); public async Task GetAuthorizationTokenAsync( Uri uri, Dictionary? additionalAuthenticationContext = null, CancellationToken cancellationToken = default) { try { var silent = _pca.AcquireTokenSilent(_scopes, _account); if (_tenantId is not null) silent = silent.WithTenantId(_tenantId); var result = await silent.ExecuteAsync(cancellationToken); return result.AccessToken; } catch (MsalUiRequiredException) { var interactive = _pca.AcquireTokenInteractive(_scopes); if (_tenantId is not null) interactive = interactive.WithTenantId(_tenantId); var result = await interactive.ExecuteAsync(cancellationToken); return result.AccessToken; } } }