問(wèn)題描述
我正在針對(duì) Azure Active Directory 對(duì)我的 Web api 用戶進(jìn)行身份驗(yàn)證.現(xiàn)在我想獲取該用戶所屬的組列表.
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.
我更改了應(yīng)用程序清單以包含
I changed application manifest to include
"groupMembershipClaims": "All",
但這所做的只是添加聲明 hasGroups 但沒(méi)有組名.
but all this does is to add claim hasGroups but no group names.
我在門(mén)戶中為我的應(yīng)用授予了 Windows Azure Active Directory 的所有 (8) 項(xiàng)委派權(quán)限.
I granted all (8) Delegated Permissions to Windows Azure Active Directory for my app in the portal.
推薦答案
我確實(shí)做到了.
讓我們將我的 Azure AD 應(yīng)用程序稱為AD-App".
Let's call my Azure AD appication "AD-App".
廣告應(yīng)用
其他應(yīng)用程序的權(quán)限設(shè)置為;
Windows Azure 活動(dòng)目錄.
Windows Azure Active Directory.
應(yīng)用程序權(quán)限:0.
委派權(quán)限 2(讀取目錄數(shù)據(jù)"、登錄并讀取用戶配置文件".
Delegated Permissions 2 ("Read directory data", "Sign in and read user profile".
Manifest 有如下設(shè)置:
"groupMembershipClaims": "SecurityGroup"
"groupMembershipClaims": "SecurityGroup"
后端 API
以下是我返回用戶組的方法.要么您發(fā)送用戶 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;
}
我不能告訴你這是否是最佳實(shí)踐,但它對(duì)我有用.
I can't tell you wether this is done by best practice or not, but it works for me.
這篇關(guān)于在聲明中獲取 Azure AD 用戶所屬的組列表的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!