我创建了一个Azure活动目录用户,并将用户添加到了app角色。 现在我正在检索此用户并尝试将其添加到更多应用程序角色。
var activeDirectoryUser = client.Users.Where(u => u.UserPrincipalName == user.UserName).ExecuteSingleAsync().Result as User;
作为预防措施,我想在添加之前首先检查用户是否已经处于app角色,但问题是ApproleAssignments
对象上的User
字段始终为空。即使您用户具有应用程序角色分配,如果我尝试将用户添加到相同的应用程序角色,我也会收到错误。
创建新的应用角色分配。
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();
检查用户是否处于应用角色。
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
库
答案 0 :(得分:3)
对于迟到的回复感到抱歉。以下代码对我有用。不确定是否需要使用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);
}
希望这会有所帮助......
答案 1 :(得分:2)
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;
}
以上代码对我有用。试试这个,希望这会有所帮助:)