Azure AD添加AppRoleAssignment

时间:2016-09-01 07:00:37

标签: azure asp.net-mvc-5 rbac azure-ad-graph-api azure-active-directory

我在Azure MV上使用MVC应用程序上的身份验证服务。我正在使用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我将放置在应用程序清单中创建的角色的IDResourceId我正在放置应用程序的ObjectId。该应用程序是在AAD目录下创建的。

代码实际上没有错误地完成,但检查用户显示的不是AppRoleAssignments

最后,我尝试使用应用程序角色实现RBAC。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

要将应用程序角色分配给用户,您需要将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)
};