首页 > 解决方案 > 如何通过 Microsoft Graph 创建 appRoleAssignment?

问题描述

根据本文档,您应该能够通过 Microsoft Graph 创建 appRoleAssignment,但这不起作用。在GitHub 问题中,我被指示在此处创建问题。我们已将大部分代码从 Azure Graph API 迁移到 Microsoft Graph,这是最后一个缺失的部分。

标签: microsoft-graph-api

解决方案


这终于对我有用了!

可能有更优化的方式来发布 JSON,但我必须深入了解基础知识,以确保没有任何东西导致这在幕后失败。

        const string ROLE_ASSIGNMENT_FORMATTER = "https://graph.microsoft.com/beta/servicePrincipals/{0}/appRoleAssignments";

        public static async Task AddApplicationUsers(string enterpriseAppId, string userId, string roleId)
        {
            HttpClient client = new HttpClient();
            string url = string.Format(ROLE_ASSIGNMENT_FORMATTER, enterpriseAppId);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());

            var roleAssignment = new
            {
                appRoleId = roleId,
                principalId = userId,
                resourceId = enterpriseAppId
            };


            var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(roleAssignment), Encoding.UTF8, "application/json");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response  = await client.PostAsync(url, content);

            if (response.IsSuccessStatusCode)
            {
                return ;
            }
            else
            {
                throw new HttpRequestException(response.ReasonPhrase);
            }
        }

推荐阅读