How to create an appRoleAssignment via Microsoft Graph?

Viewed 785

As per this documentation you should be able to create an appRoleAssignment via Microsoft Graph, however this doesn't work. In a GitHub issue I was instructed to create the issue here. We have migrated most of our code from Azure Graph API to Microsoft Graph and this is the last piece that is missing.

1 Answers

This finally worked for me!

There might be more optimized ways to post the JSON but I had to go to basics to make sure nothing is causing this to fail behind the scenes.

        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);
            }
        }
Related