問題描述
我正在針對 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".
廣告應用
其他應用程序的權限設置為;
Windows Azure 活動目錄.
Windows Azure Active Directory.
應用程序權限:0.
委派權限 2(讀取目錄數據"、登錄并讀取用戶配置文件".
Delegated Permissions 2 ("Read directory data", "Sign in and read user profile".
Manifest 有如下設置:
"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 用戶所屬的組列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!