Azure AD 添加 AppRoleAssignment

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

我正在使用 Azure AD 在 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b7b6a7c7b6a7d4f7b6a7c7b216c6062" rel="noreferrer noopener nofollow">[email protected]</a>";
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 我正在放置在应用程序 list 中创建的角色的IDResourceId 我正在放置应用程序的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)
};

关于Azure AD 添加 AppRoleAssignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39264685/

相关文章:

azure - 部署到 Azure 网站时可能导致 EvoPDF "unable to render html"异常的原因

asp.net-mvc-5 - MVC5 上的 ReactJS.Net 无法解决依赖关系

c# - MVC 5 Identity 2.0 在登录时显示配置文件完成情况

azure - 更新到 Storage 2.1.0.3 后在 MVC 中返回 Blob 流时出现 NullReferenceException

azure 网站被暂停,我不明白为什么。

kubernetes - 如何将相同的 RBAC 角色分配给两个不同的 IAM 角色以访问 EKS 中的集群?

具有观察事件权限的 Kubernetes 集群角色

国家/地区域的 Azure DNS

javascript - 如果用户存在,请使用数据库表中的数据填写表单文本框?