![](/img/trans.png)
[英]How to get all users that belong in an AppRole using Azure Active Directory Graph API
[英]How to check if an azure active directory user is already in an approle
我创建了一个Azure活动目录用户,并将用户添加到了app角色。 现在我正在检索此用户并尝试将其添加到更多应用程序角色。
var activeDirectoryUser = client.Users.Where(u => u.UserPrincipalName == user.UserName).ExecuteSingleAsync().Result as User;
作为预防措施,我想在添加之前首先检查用户是否已经处于app角色,但问题是User
对象上的ApproleAssignments
字段始终为空。 即使您用户具有应用程序角色分配,如果我尝试将用户添加到相同的应用程序角色,我也会收到错误。
创建新的应用角色分配。
var appRoleAssignment = new AppRoleAssignment
{
Id = appRole.Id,
ResourceId = Guid.Parse(servicePrincpal.ObjectId),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};
if(IsUserInAppRole(user,appRoleAssignment))return;
user.AppRoleAssignments.Add(appRoleAssignment);
user.UpdateAsync().Wait();
检查用户是否处于app角色。
private bool IsUserInAppRole(User user, AppRoleAssignment appRoleAssignment)
{
var userInApprole = user.AppRoleAssignments.Where(ara => ara.ObjectId == appRoleAssignment.Id.ToString());
return userInApprole.Any();
}
我正在使用最新版本的Microsoft.Azure.ActiveDirectory.GraphClient
库
回复晚了非常抱歉。 以下代码对我有用。 不确定是否需要使用IUserFetcher接口,但LINQ查询失败,因为您正在将赋值的objectID与appRole Id进行比较。 您需要比较的是作业的ID。
var userFetcher = user as IUserFetcher;
IPagedCollection<IAppRoleAssignment> rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();
IAppRoleAssignment a = null;
a = assignments.Where(ara => ara.Id.Equals(appRole.Id)).First();
if (a != null) {
Console.WriteLine("Found assignment {0} for user {1}", appRole.Id, user.DisplayName);
}
希望这可以帮助...
var userFetcher = user as IUserFetcher;
IPagedCollection rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();
上面的代码行导致异常,因为未执行转换,如果将其转换为:
IPagedCollection rawObjects =
(IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments =
(IList<IAppRoleAssignment>)rawObjects.CurrentPage.ToList();
代码编译成功,但运行时异常如下:
无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IList'。 存在显式转换(您是否错过了演员?)
你能指导一下如何使用这两个陈述吗?
更新:
private static bool IsUserInRole(User user, AppRole appRole, bool roleAlreadyAssigned = false)
{
var userFetcher = user as IUserFetcher;
IPagedCollection rawObjects = (IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;
foreach (IAppRoleAssignment item in rawObjects.CurrentPage)
{
if (item.Id == appRole.Id)
{
roleAlreadyAssigned = true; break;
}
}
return roleAlreadyAssigned;
}
上面的代码对我有用。 试试这个,希望这会有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.