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. /// public async Task CreateClientAsync(string clientId, CancellationToken ct) { var pca = await _msalFactory.GetOrCreateAsync(clientId); var accounts = await pca.GetAccountsAsync(); var account = accounts.FirstOrDefault(); var graphScopes = new[] { "https://graph.microsoft.com/.default" }; var tokenProvider = new MsalTokenProvider(pca, account, graphScopes); 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; public MsalTokenProvider(IPublicClientApplication pca, IAccount? account, string[] scopes) { _pca = pca; _account = account; _scopes = scopes; } public AllowedHostsValidator AllowedHostsValidator { get; } = new(); public async Task GetAuthorizationTokenAsync( Uri uri, Dictionary? additionalAuthenticationContext = null, CancellationToken cancellationToken = default) { try { var result = await _pca.AcquireTokenSilent(_scopes, _account) .ExecuteAsync(cancellationToken); return result.AccessToken; } catch (MsalUiRequiredException) { // If silent fails, try interactive var result = await _pca.AcquireTokenInteractive(_scopes) .ExecuteAsync(cancellationToken); return result.AccessToken; } } }