获取每个应用程序的所有用户 Azure Active Directory .NET Web Api C#

Getting all users per application Azure Active Directory .NET Web Api C#

我正在尝试使用 .NET Web API C# 访问我在 Azure Active Directory 中的应用程序中的用户。 我试图从客户端获取用户:

await this.aadClient.Users.ExecuteAsync()

但它获取了 AD 中的所有用户,而不是每个应用程序。 我尝试获取应用程序的成员:

var apps = await this.aadClient.Applications.Where(x => x.AppId == this.appId)
                                    .Expand(x => x.Members).ExecuteAsync();
var app = apps.CurrentPage.FirstOrDefault();
var members = app.Members.CurrentPage;

但是尽管appId是正确的,而且我的应用程序中有19个用户,但结果总是空的。

有人知道问题出在哪里吗?


编辑

获取客户​​:

var context = new AuthenticationContext($"https://login.microsoftonline.com/[tenant]", false);

var aadClient = new ActiveDirectoryClient(
                new Uri(new Uri("https://graph.windows.net"), [tenant]),
                async () => await context.AcquireTokenAsync("https://graph.windows.net", new ClientCredential([clientId], [clientSecret])));

广告图客户端调用广告图 api,api 为您的应用程序分配用户是

https://graph.windows.net/{tenant}/servicePrincipals/{servicePrincipalId}6f/appRoleAssignedTo

所以代码应该是

aadClient.ServicePrincipals.GetByObjectId("").AppRoleAssignedTo

您可以找到如下服务servicePrincipalId。它是您的企业应用程序的 ObjectId。

Directory.Read.All 需要权限。点击App registrations->找到你的application(同一个提供clientId的)->API permission

记得点击 Grant admin consent 按钮,因为此权限需要管理员同意。

更新: 我可以成功将用户分配给应用程序,这是测试代码。

using System;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace ConsoleApp13
    {
        class Program
        {
            static void Main(string[] args)
            {
                Uri servicePointUri = new Uri("https://graph.windows.net");
                Uri serviceRoot = new Uri(servicePointUri, "{tenant}");  
                var aadClient = new ActiveDirectoryClient(
                                serviceRoot,
                                 getToken);

                var a = aadClient.ServicePrincipals.GetByObjectId("{objectId}").AppRoleAssignedTo.ExecuteAsync().Result;
                Console.WriteLine(a.CurrentPage.Count);

            }

            public static async Task<string> getToken()
            {
                var context = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}", false);
                return context.AcquireTokenAsync("https://graph.windows.net", new ClientCredential("{client_id}", "{client_secret}")).Result.AccessToken;
            }
        }
    }

确保您已向您的应用授予 Directory.Read.All 权限。您可以通过 decoding the token.

在访问令牌中查看它