簡體   English   中英

.Net在桌面上的Azure Graph API將無法進行身份驗證

[英]Azure Graph API in .Net on desktop will not authenticate

每當我嘗試使用Microsoft圖形API與Azure AD進行通信時,都不會打開瀏覽器窗口。

如果我下載了使用UWP的示例,則它可以正常工作,但是當我嘗試在現有應用程序(不是UWP)中實現相同代碼時,它將無法工作。 我也嘗試過使用.net 4.6.1制作一個簡單的控制台應用程序,並且不會彈出任何瀏覽器窗口。 如果我在DelegateAuthenticationProvider中放置一個斷點,它將永遠不會被擊中。 如果我直接調用GetTokenForUserAsync,則執行將無限期地與IdentityClientApp.AcquireTokenAsync保持一致。

這僅是為了在UWP項目上工作還是我做錯了什么?

using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Graph;
using Microsoft.Identity.Client;

namespace ConsoleApp1
{
    public class AuthenticationHelper
    {
        // The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.
        static string clientId =     System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"].ToString();
        public static string[] Scopes = { "User.Read", "Mail.Send", "Files.ReadWrite" };

        public static PublicClientApplication IdentityClientApp = new         PublicClientApplication(clientId);

        public static string TokenForUser = null;
        public static DateTimeOffset Expiration;

        private static GraphServiceClient graphClient = null;

        // Get an access token for the given context and resourceId. An attempt is first made to 
        // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
        public static GraphServiceClient GetAuthenticatedClient()
        {
            if (graphClient == null)
            {
                // Create Microsoft Graph client.
                try
                {
                    graphClient = new GraphServiceClient(
                        "https://graph.microsoft.com/v1.0",
                        new DelegateAuthenticationProvider(
                            async (requestMessage) =>
                            {
                                var token = await GetTokenForUserAsync();
                                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                                // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.
                                requestMessage.Headers.Add("SampleID", "uwp-csharp-connect-sample");

                            }));
                    return graphClient;
                }

                catch (Exception ex)
                {
                }
            }

            return graphClient;
        }


        /// <summary>
        /// Get Token for User.
        /// </summary>
        /// <returns>Token for user.</returns>
        public static async Task<string> GetTokenForUserAsync()
        {
            Microsoft.Identity.Client.AuthenticationResult authResult;
            try
            {
                authResult = await     IdentityClientApp.AcquireTokenSilentAsync(Scopes,     IdentityClientApp.Users.First());
                TokenForUser = authResult.AccessToken;
            }

            catch (Exception)
            {
                if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
                {
                    authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);

                    TokenForUser = authResult.AccessToken;
                    Expiration = authResult.ExpiresOn;
                }
            }

            return TokenForUser;
        }

        /// <summary>
        /// Signs the user out of the service.
        /// </summary>
        public static void SignOut()
        {
            foreach (var user in IdentityClientApp.Users)
            {
                IdentityClientApp.Remove(user);
            }
            graphClient = null;
            TokenForUser = null;

        }

    }
}

為了理解使用Graph API的身份驗證,我使用此示例(不是UWP而是WPF)

https://github.com/Azure-Samples/active-directory-dotnet-desktop-msgraph-v2/blob/master/README.md

這非常簡單,它可以幫助我了解獲取身份驗證令牌的兩種不同方式的行為: AcquireTokenSylentAsync() (無需與用戶交互)和AcquireTokenAsync() (為用戶登錄打開瀏覽器)

根據您的描述,我在.NET 4.6.1上創建了我的控制台應用程序目標,並使用MSAL進行身份驗證,並利用Microsoft Graph .NET客戶端庫與Microsoft Graph API進行通信。

我重用了GetTokenForUserAsync方法,並按如下所示執行了我的代碼段:

static void Main(string[] args)
{
    MainAsync(args).GetAwaiter().GetResult();
}

static async Task MainAsync(string[] args)
{
    var graphClient = new GraphServiceClient(
                "https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        var token = await GetTokenForUserAsync();
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                    }));

    var user = await graphClient.Me.Request().GetAsync();
    Console.WriteLine(JsonConvert.SerializeObject(user));
}

要么

static void Main(string[] args)
{
    var graphClient = new GraphServiceClient(
                "https://graph.microsoft.com/v1.0",
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        var token = await GetTokenForUserAsync();
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                    }));

    var user = graphClient.Me.Request().GetAsync().Result;
    Console.WriteLine(JsonConvert.SerializeObject(user));
    Console.WriteLine("press any key to exit...");
    Console.ReadLine();
}

測試:

在此處輸入圖片說明

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM