Comment authentifier l'application UWP «Live SDK» par rapport à Microsoft Graph

Sep 29 2020

J'ai mis à niveau mon application UWP du SDK OneDrive vers le SDK Microsoft Graph. L'application a été enregistrée plus tôt àhttps://apps.dev.microsoft.com/ (sous "Applications Live SDK").

J'ai implémenté la nouvelle authentification à l'aide de MSAL.NET (package NuGet Microsoft.Identity.Client). Voici le code que j'utilise pour l'authentification:

    public class AuthenticationService
    {
        private const string Tenant = "common"; 
        private const string Authority = "https://login.microsoftonline.com/" + Tenant;
    
        private const string MSGraphURL = "https://graph.microsoft.com/v1.0/";
        private const string RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";
    
        private readonly string[] scopes;
    
        private readonly IPublicClientApplication publicClientApp;
    
        private GraphServiceClient graphClient;
    
        private AuthenticationResult authResult;
    
        public AuthenticationService(string clientId, string[] scopes)
        {
            this.scopes = scopes;
    
            this.publicClientApp = PublicClientApplicationBuilder.Create(clientId)
                .WithAuthority(Authority)
                .WithUseCorporateNetwork(false)
                .WithRedirectUri(RedirectUri)
                    .WithLogging((level, message, containsPii) =>
                    {
                        Debug.WriteLine($"MSAL: {level} {message} ");
                    }, Microsoft.Identity.Client.LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
                .Build();
        }
        public string TokenForUser => authResult?.AccessToken;
    
        public DateTimeOffset? TokenExpireOn => authResult?.ExpiresOn;
    
        public GraphServiceClient SignIn()
        {
            if (graphClient == null)
            {
                graphClient = new GraphServiceClient(MSGraphURL,
                    new DelegateAuthenticationProvider(async (requestMessage) =>
                    {
                        if (string.IsNullOrEmpty(TokenForUser))
                        {
                            authResult = await AuthenticateAsync();
                        }
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", TokenForUser);
                    }));
            }
    
            return graphClient;
        }
    
        public async Task SignOutAsync()
        {
            try
            {
                authResult = null;
                graphClient = null;
    
                foreach (IAccount account in await publicClientApp.GetAccountsAsync().ConfigureAwait(false))
                {
                    await publicClientApp.RemoveAsync(account).ConfigureAwait(false);
                }
            }
            catch (MsalException ex)
            {
                Log.Exception(ex);
            }
        }
    
        private async Task<AuthenticationResult> AuthenticateAsync()
        {
            IEnumerable<IAccount> accounts = await publicClientApp.GetAccountsAsync().ConfigureAwait(false);
            IAccount firstAccount = accounts.FirstOrDefault();
    
            AuthenticationResult authResult;
            try
            {
                authResult = await publicClientApp.AcquireTokenSilent(scopes, firstAccount)
                                                    .ExecuteAsync().ConfigureAwait(false);
            }
            catch (MsalUiRequiredException ex)
            {
                Log.Exception(ex);
    
                authResult = await publicClientApp.AcquireTokenInteractive(scopes)
                                                    .ExecuteAsync()
                                                    .ConfigureAwait(false);
    
            }
            return authResult;
        }
    }

Le code ci-dessus ne fonctionne que si j'inscris mon application dans Azure Portal et que j'obtiens la nouvelle à clientIdpartir de là. Essayer d'utiliser l'ancien ID d'application entraîne cette exception:

Microsoft.Identity.Client.MsalClientException: 'Error: ClientId is not a Guid.'

Je ne peux pas renouveler l'enregistrement de mon application car l'application utilise le dossier d'application ( Files.ReadWrite.AppFolder) et la réinscription de l'application entraînerait la perte de données des utilisateurs existants.

Alors, comment authentifier mon application par rapport à l'API Microsoft Graph à l'aide de l'ancien identifiant d'application "Application SDK Live" et de préférence en utilisant le compte Windows actuel (aucune interface utilisateur de connexion requise)?

Réponses

AlfredoR Oct 01 2020 at 18:45

Vous devez créer une nouvelle inscription d'application dans le portail Azure . Vous devez également vous connecter à l'aide d'un compte professionnel ou scolaire ou d'un compte personnel (Microsoft) via l'un des flux MSAL pris en charge . Files.ReadWrite.AppFolder est une autorisation. L'ajouter à une nouvelle application ne supprimera ni ne perdra rien.