如何验证“Live SDK"针对 Microsoft Graph 的 UWP 应用程序 [英] How to authenticate "Live SDK" UWP application against Microsoft Graph

查看:117
本文介绍了如何验证“Live SDK"针对 Microsoft Graph 的 UWP 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的 UWP 应用从 OneDrive SDK 升级到 Microsoft Graph SDK.该应用程序之前已在 https://apps.dev.microsoft.com/(在实时 SDK 应用程序").

I upgraded my UWP app from OneDrive SDK to Microsoft Graph SDK. The app has been registered earlier at https://apps.dev.microsoft.com/ (under "Live SDK applications").

我已经使用 MSAL.NET(NuGet 包 Microsoft.Identity.Client)实现了新的身份验证.这是我用于身份验证的代码:

I have implemented the new authentication using MSAL.NET (NuGet package Microsoft.Identity.Client). Here is the code I use for authentication:

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

仅当我在 Azure 门户中注册我的应用程序并从那里获取新的 clientId 时,以上代码才有效.尝试使用旧的应用程序 ID 会导致此异常:

Above code works only if I register my app in Azure Portal and get the new clientId from there. Trying to use the old application ID results this exception:

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

我无法续订我的应用注册,因为该应用正在使用应用文件夹 (Files.ReadWrite.AppFolder),再次注册该应用会导致现有用户丢失他们的数据.

I cannot renew my app registration as the app is using app folder (Files.ReadWrite.AppFolder) and registering the app again would result existing users to loose their data.

那么我如何使用旧的Live SDK 应用程序"针对 Microsoft Graph API 对我的应用程序进行身份验证?应用 ID 并且最好使用当前的 Windows 帐户(无需登录 UI)?

So how do I authenticate my app against the Microsoft Graph API using the old "Live SDK application" App Id and preferably using the current Windows account (no sign in UI required)?

推荐答案

您需要在 Azure 门户.您还需要使用工作或学校帐户或个人 (Microsoft) 帐户通过 支持的 MSAL 流程.Files.ReadWrite.AppFolder 是一种权限.将其添加到新应用程序不会删除或丢失任何内容.

You need to create a new app registration in the Azure Portal. Also you need to login using a work or school account or personal (Microsoft) account trough one of the supported MSAL flows. Files.ReadWrite.AppFolder is a permission. Adding it to a new application won't delete or loose anything.

这篇关于如何验证“Live SDK"针对 Microsoft Graph 的 UWP 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆