如何使用graph api 1.5在azure active directory中为用户分配应用程序角色



我在azure活动目录中为用户添加应用程序角色时遇到了一个问题。在用户模型中,有一个名为ApproveAssignment的属性,我认为我可以在其中为用户设置应用程序角色。但当我做到这一点时,它并没有分配。有人能帮我吗?

我使用应用程序模型中的应用程序角色添加了应用程序角色。创建用户时,我可以通过下拉菜单进行填充。下面显示了创建用户的部分。AppRoleAssignment中的ResourceId应该是什么?

 [HttpPost]
        public async Task<ActionResult> Create(UserModel user)
        {
            ActiveDirectoryClient client = null;
            try
            {
                client = AuthenticationHelper.GetActiveDirectoryClient();
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext()
                        .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }
                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View();
            }
            try
            {
                User mappedUser = MapToUser(user);
                await client.Users.AddUserAsync(mappedUser);
                await AddUserRole(mappedUser, user);
                return RedirectToAction("Index");
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return View();
            }
        }
        /// <summary>
        /// Adds the user role.
        /// </summary>
        /// <param name="mappedUser">The mapped user.</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        private async Task AddUserRole(User mappedUser, UserModel model)
        {
            ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
            IPagedCollection<IUser> pagedCollection = await client.Users.ExecuteAsync();
            var currentUser = pagedCollection.CurrentPage.Where(x => x.UserPrincipalName.Equals(mappedUser.UserPrincipalName)).FirstOrDefault();
            var appRoleAssignment = new AppRoleAssignment();
            appRoleAssignment.Id = model.AppRoleId;
            appRoleAssignment.PrincipalId = Guid.Parse(currentUser.ObjectId);
            appRoleAssignment.ResourceId = Guid.Parse(clientId);
            ////((ClaimsIdentity)ClaimsPrincipal.Current.Identity).AddClaim(
            ////    new Claim(ClaimTypes.Role, "Manager", ClaimValueTypes.String, "GRAPH"));
            await currentUser.UpdateAsync();
            ////Remaining have to be completed.
        }
        /// <summary>
        /// Maps to user.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        private Microsoft.Azure.ActiveDirectory.GraphClient.User MapToUser(UserModel model)
        {
            var user = new User();
            user.UserPrincipalName = model.UserPrincipalName;
            user.AccountEnabled = model.AccountEnabled;
            user.PasswordProfile = model.PasswordProfile;
            user.MailNickname = model.MailNickname;
            user.DisplayName = model.DisplayName;
            user.GivenName = model.GivenName;
            user.Surname = model.Surname;
            user.JobTitle = model.JobTitle;
            user.Department = model.Department;
            return user;
        }

很抱歉,我很难理解您的代码,因为其中一些代码丢失了(比如您对应用程序的定义及其声明的任何应用程序角色)。在高层,应用程序将定义一系列应用程序角色(appRoles)。一旦用户同意该应用程序,表示该应用程序的应用程序实例将出现在同意的租户中。如果您想在指定的应用程序角色之一中将用户分配给该应用程序,则需要对该用户设置appRoleAssignment(选择应用程序角色id和资源id-应用程序的id)。appRoleAssignment及其属性描述如下:https://msdn.microsoft.com/en-us/library/azure/dn835128.aspx以及此处描述的REST API示例http://blogs.msdn.com/b/aadgraphteam/archive/2014/12/12/announcing-the-new-version-of-graph-api-api-version-1-5.aspx.

此外,我们还有一个控制台示例,它显示了在应用程序上创建appRole,以及将应用程序(在声明的应用程序角色中)分配给用户。您可以在github上找到:https://github.com/AzureADSamples/ConsoleApp-GraphAPI-DotNet

HTH、

代码中的资源ID是错误的:

appRoleAssignment.ResourceId = Guid.Parse(clientId);

图形应用程序使用的资源是与应用程序关联的服务原则的ID。你可以在这里阅读应用程序和服务原则之间的区别,但简单地说,clientID是应用程序定义的ID,而据我所知,服务原则是它的一个活动实例。因此,你需要的ID是进行角色分配的服务原则的objectID。一些获取服务原理ID的测试代码如下所示:

var servicePrincipleList = await client.ServicePrincipals.Where(e => e.AppId == clientId).ExecuteAsync();
var roleResourceUpdateID = servicePrincipleList.CurrentPage.First().ObjectId;

这就是您需要在角色分配中使用的对象ID。

最新更新