2016-02-11 74 views
3

我正在针对Azure Active Directory对我的web api的用户进行身份验证。 现在我想获得该用户所属的组的列表。获取Azure AD用户所属的组列表中的声明

我改变了应用程序清单包括

"groupMembershipClaims": "All", 

但所有这确实是增加要求hasGroups但没有组名。

我在门户网站中为我的应用授予了Windows Azure Active Directory的全部(8)委托权限。

回答

4

我已经完成了这个。

让我们打电话给我的Azure AD Appication“AD-App”。

AD-应用

权限到其它应用程序被设置为;

Windows Azure Active Directory。

应用权限:0.

委托权限2( “读取目录数据”, “登录和读的用户简档”

清单具有以下设置:

“groupMembershipClaims”:“SecurityGroup”

后端API

以下是我返回用户组的方法。您可以发送用户标识,如果没有,则使用来自声明的标识。 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; 
    } 

我不能告诉你这是通过最佳实践或不是,但它适用于我。

+0

对于这个任何读者来说一个重要的注意事项:后端API方法在写入时不会检索传递组成员资格。通过AD门户配置的前一种方法确实如此。 –

+1

谢谢为我工作:-) – Saurabh

+0

如果您在上面的示例中包含了必要的名称空间,那将会很好。 – LarryBud

0

如果用户拥有超过150个组,则只返回calim中Graph API的链接,如“graph:link”,而不是组。这是出于性能原因完成的。然后您需要调用Graph API(MS Graph API - 最新版本或AD Graph API - 较旧版本)来遍历所有组。

相关问题