首页 > 解决方案 > 使用 GraphServiceClient 查询 Azure AD

问题描述

我想使用 GraphServiceClient 为用户查询 Azure Active Directory。

我在 Azure 门户上注册了一个应用程序并取回了一个令牌。现在我想获取我的 ActiveDirectory 的用户,但不明白如何查询 Azure AD

  static async void Works() //gets a token 
        {
            try
            {
                var tenantId = "myTenant";
                var clientId = "myId";
                var clientSecret = @"MySecret";

                // Configure app builder
                var authority = $"https://login.microsoftonline.com/{tenantId}";
                var app = ConfidentialClientApplicationBuilder
                    .Create(clientId)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(new Uri(authority))
                    .Build();

                // Acquire tokens for Graph API
                var scopes = new[] { "https://graph.microsoft.com/.default" };
                var authenticationResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();

                // Create GraphClient and attach auth header to all request (acquired on previous step)
                var graphClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(requestMessage =>
                    {
                        requestMessage.Headers.Authorization =
                            new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);

                        return Task.FromResult(0);
                    }));

                // Call Graph API
                //HOW DO I QUERY AZURE AD????
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }

标签: c#azure

解决方案


如果要列出用户,可以使用如下代码。

 var users = await graphClient.Users
                .Request()
                .GetAsync();

在此处输入图像描述

有关更多详细信息,请参阅此链接


推荐阅读