为了账号安全,请及时绑定邮箱和手机立即绑定

获取每个应用程序的所有用户 Azure Active Directory

获取每个应用程序的所有用户 Azure Active Directory

C#
小怪兽爱吃肉 2023-07-09 15:17:08
我正在尝试使用 .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])));
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

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

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

所以代码应该是

aadClient.ServicePrincipals.GetByObjectId("").AppRoleAssignedTo

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

//img1.sycdn.imooc.com/64aa5f1f0001989306530402.jpg

Directory.Read.All需要许可。点击应用注册->找到您的应用程序(与提供clientId的应用程序相同)->API权限

//img4.sycdn.imooc.com/64aa5f2a000187bd06500590.jpg

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

//img2.sycdn.imooc.com/64aa5f3a0001c8ea05780245.jpg

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


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您的应用程序权限。您可以通过解码令牌在访问令牌中检查它。

//img4.sycdn.imooc.com/64aa5f4d0001d0e505530410.jpg


查看完整回答
反对 回复 2023-07-09
  • 1 回答
  • 0 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信