获取声明中Azure AD用户所属的组的列表 [英] Get a list of groups that Azure AD user belongs to in claims

查看:250
本文介绍了获取声明中Azure AD用户所属的组的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在针对Azure Active Directory验证我的Web api用户。
现在,我想获取该用户所属的组的列表。

I am authenticating users of my web api against Azure Active Directory. Now I want to get a list of groups that this user belongs.

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

I changed application manifest to include

"groupMembershipClaims": "All",

,但这只是添加声明hasGroups而没有组名。

but all this does is to add claim hasGroups but no group names.

我已为门户中的应用授予Windows Azure Active Directory的所有(8)委派权限。

I granted all (8) Delegated Permissions to Windows Azure Active Directory for my app in the portal.

推荐答案

我已经做到了。

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

Let's call my Azure AD appication "AD-App".

AD-App

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

Windows Azure Active Directory。

Windows Azure Active Directory.

应用程序权限:0。

委托权限2 (读取目录数据,登录并读取用户个人资料。

Delegated Permissions 2 ("Read directory data", "Sign in and read user profile".

清单具有以下设置:

groupMembershipClaims: SecurityGroup

"groupMembershipClaims": "SecurityGroup"

后端API

以下是我返回用户组的方法:您可以发送用户ID,如果不是,则使用声明中的ID。ID表示 objectIdentifier。

The following is my method to return the users groups. Either you send in the users id, if not it uses the id from claims. Id meaning "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;
    }

我无法告诉您是否通过最佳实践来做到这一点,但这对我有用。

I can't tell you wether this is done by best practice or not, but it works for me.

这篇关于获取声明中Azure AD用户所属的组的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆