Get a list of groups that Azure AD user belongs to in claims

前端 未结 4 1753
野趣味
野趣味 2020-12-06 07:27

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

4条回答
  •  情深已故
    2020-12-06 08:01

    I've done exactly this.

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

    AD-App

    Permissions to other applications is set to;

    Windows Azure Active Directory.

    Application Permissions: 0.

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

    Manifest has the following setting:

    "groupMembershipClaims": "SecurityGroup"

    Backend API

    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 GetGroupMembershipsByObjectId(string id = null)
        {
            if (string.IsNullOrEmpty(id))
                id = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
    
            IList groupMembership = new List();
            try
            {
                ActiveDirectoryClient activeDirectoryClient = ActiveDirectoryClient;
                IUser user = activeDirectoryClient.Users.Where(u => u.ObjectId == id).ExecuteSingleAsync().Result;
                var userFetcher = (IUserFetcher)user;
    
                IPagedCollection pagedCollection = userFetcher.MemberOf.ExecuteAsync().Result;
                do
                {
                    List 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.

提交回复
热议问题