获取Azure AD用户在声明中所属的组列表

jlp*_*jlp 7 .net azure-active-directory adal azure-ad-graph-api

我正在对Azure Active Directory的web api用户进行身份验证.现在我想获得该用户所属的组列表.

我更改了应用程序清单以包含

"groupMembershipClaims": "All",
Run Code Online (Sandbox Code Playgroud)

但所有这一切都是添加声明hasGroups但没有组名.

我在门户网站中为我的应用程序授予了Windows Azure Active Directory的所有(8)委托权限.

小智 8

我做到了这一点.

我们将我的Azure AD应用称为"AD-App".

AD-应用

其他应用程序的权限设置为;

Windows Azure Active Directory.

申请权限:0.

委托权限2("读取目录数据","登录并读取用户配置文件".

清单具有以下设置:

"groupMembershipClaims":"SecurityGroup"

后端API

以下是我返回用户组的方法.您是否发送了用户ID,如果不是,则使用声明中的ID.Id表示"objectIdentifier".

        public static IEnumerable<string> GetGroupMembershipsByObjectId(string id = null)
    {
        if (string.IsNullOrEmpty(id))
            id = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        IList<string> groupMembership = new List<string>();
        try
        {
            ActiveDirectoryClient activeDirectoryClient = ActiveDirectoryClient;
            IUser user = activeDirectoryClient.Users.Where(u => u.ObjectId == id).ExecuteSingleAsync().Result;
            var userFetcher = (IUserFetcher)user;

            IPagedCollection<IDirectoryObject> pagedCollection = userFetcher.MemberOf.ExecuteAsync().Result;
            do
            {
                List<IDirectoryObject> directoryObjects = pagedCollection.CurrentPage.ToList();
                foreach (IDirectoryObject directoryObject in directoryObjects)
                {
                    if (directoryObject is Group)
                    {
                        var group = directoryObject as Group;
                        groupMembership.Add(group.DisplayName);
                    }
                }
                pagedCollection = pagedCollection.GetNextPageAsync().Result;
            } while (pagedCollection != null);

        }
        catch (Exception e)
        {
            ExceptionHandler.HandleException(e);
            throw e;
        }

        return groupMembership;
    }
Run Code Online (Sandbox Code Playgroud)

我不能告诉你,这是通过最佳实践做到的,但它适用于我.

  • `ActiveDirectoryClient activeDirectoryClient = ActiveDirectoryClient` 这一行不起作用。 (2认同)

小智 0

您向您的应用授予了哪些权限?您需要明确请求读取组的能力(请参阅https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-中的group.read.all)权限范围)。截至今天,这些权限只能得到管理员的同意。