我在MVC应用程序上使用Azure AD的身份验证服务。我正在使用Graph API成功地管理用户帐户。我正在尝试为用户添加一个AppRoleAssignment
。
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await GetTokenForApplication());
IUser user = new User();
user.JobTitle = "Tester";
user.DisplayName = "Test Tester";
user.Surname = "Tester";
user.GivenName = "Test";
user.UserPrincipalName = "ttester@test.com";
user.AccountEnabled = true;
user.MailNickname = "ttester";
user.PasswordProfile = new PasswordProfile
{
Password = "XXXXX",
ForceChangePasswordNextLogin = true
};
await activeDirectoryClient.Users.AddUserAsync(user);
var appRoleAssignment = new AppRoleAssignment
{
Id = Guid.Parse("XXXXX"),
ResourceId = Guid.Parse("XXXXX"),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};
user.AppRoleAssignments.Add(appRoleAssignment);
await user.UpdateAsync();
AppRoleAssignment
从未生成。我不确定它是否是构造函数变量。
id
我正在放置角色的ID
,在应用程序清单中创建。ResourceId
我正在放置应用程序的ObjectId
。应用程序在AAD目录下创建。
代码实际上没有错误地完成,但是检查用户时显示的不是AppRoleAssignments
。
最后,我尝试使用应用程序角色来实现RBAC。
要将应用程序角色分配给用户,需要将User
对象强制转换为IUserFetcher
:
await ((IUserFetcher)user)
.AppRoleAssignments.AddAppRoleAssignmentAsync(appRoleAssignment);
我还必须将ResourceId设置为ServicePrincipal.ObjectId
var servicePrincipal = (await
activeDirectoryClient.ServicePrincipals.Where(
s => s.DisplayName == "MyApplicationName").ExecuteAsync()).CurrentPage
.First();
var appRoleAssignment = new AppRoleAssignment
{
Id = Guid.Parse("XXXXX"),
// Service principal id go here
ResourceId = Guid.Parse(servicePrincipal.ObjectId),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};