2016-02-11 140 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 - 較舊版本)來遍歷所有組。

相關問題