简体   繁体   English

.Net在桌面上的Azure Graph API将无法进行身份验证

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

Whenever I try to use the microsoft graph api to communicate with azure AD, no browser window will open up. 每当我尝试使用Microsoft图形API与Azure AD进行通信时,都不会打开浏览器窗口。

If I download a sample that uses UWP it works correctly but when I try to implement that same code in my existing application (which is not UWP) it will not work. 如果我下载了使用UWP的示例,则它可以正常工作,但是当我尝试在现有应用程序(不是UWP)中实现相同代码时,它将无法工作。 I have also tried making a simple console application using .net 4.6.1 and again no browser window will pop up. 我也尝试过使用.net 4.6.1制作一个简单的控制台应用程序,并且不会弹出任何浏览器窗口。 If I put a breakpoint in the DelegateAuthenticationProvider it is never hit. 如果我在DelegateAuthenticationProvider中放置一个断点,它将永远不会被击中。 If I call GetTokenForUserAsync directly then execution stays on the line with IdentityClientApp.AcquireTokenAsync indefinitely. 如果我直接调用GetTokenForUserAsync,则执行将无限期地与IdentityClientApp.AcquireTokenAsync保持一致。

Is this only meant to work on UWP projects or am I doing something wrong? 这仅是为了在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;

        }

    }
}

To understand the authentication with Graph API i use this sample ( that is not a UWP but a WPF) 为了理解使用Graph API的身份验证,我使用此示例(不是UWP而是WPF)

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

It's very simple and it helps me to understand the behaviour of the two different ways to get an authentication token: AcquireTokenSylentAsync() ( with no interaction with the user ) and AcquireTokenAsync() ( that opens the browser for the user login ) 这非常简单,它可以帮助我了解获取身份验证令牌的两种不同方式的行为: AcquireTokenSylentAsync() (无需与用户交互)和AcquireTokenAsync() (为用户登录打开浏览器)

According to your description, I created my console application targets on .NET 4.6.1 and use MSAL for authentication and leverage Microsoft Graph .NET Client Library to communicate with Microsoft Graph API. 根据您的描述,我在.NET 4.6.1上创建了我的控制台应用程序目标,并使用MSAL进行身份验证,并利用Microsoft Graph .NET客户端库与Microsoft Graph API进行通信。

I reused your GetTokenForUserAsync method and executed my code snippet as follows: 我重用了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));
}

Or 要么

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

TEST: 测试:

在此处输入图片说明

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在SharePoint Online from Azure Function with API Graph中正确认证? - How to authenticate correctly in SharePoint Online from Azure Function with API Graph? 是否可以使用用户名和密码对图形 API 进行身份验证,而无需在 Azure AD 中注册应用程序 - Is there way to authenticate to Graph API using Username and Password without Application Registration in Azure AD 使用Azure Active Directory验证ASP.NET Core 2.1 Web API和使用Entity Framework验证Azure SQL - Authenticate ASP.NET Core 2.1 Web API with Azure Active Directory and Azure SQL with Entity Framework ASP NET API - 使用 Azure AD SAML 协议验证用户,无需打开 Microsoft 登录页面 - ASP NET API - Authenticate users using Azure AD SAML Protocol without open Microsoft Login Page Azure API服务器无法验证请求 - Azure API The server failed to authenticate the request 使用ADAL对Azure API App进行身份验证 - Authenticate to Azure API App using ADAL Azure REST API - 服务器无法进行身份验证 - Azure REST API - Server failed to authenticate 有没有一种简单的方法可以使用Office 365 API对WPF桌面应用程序进行身份验证? - Is there a simple way to authenticate WPF Desktop application with Office 365 API? 使用Xamarin Studio身份验证到Azure AD并连接到Microsoft Graph for iOS - Using Xamarin Studio to authenticate to Azure AD and connect to Microsoft Graph for iOS 带有Graph Api的Azure Functions计时器 - Azure Functions Timer with Graph Api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM