Umer Qureshi
Umer Qureshi

Reputation: 1766

Azure AD Graph - AppRole Creation using Application Credential Flow

I am creating a new role in azure application using Azure AD Graph API. what i'm doing is getting access token from azure using this code:

ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResourceID, clientCredential);
return authenticationResult.AccessToken;

And Creating Role using following code:

//Fetch application Data from azure AD
IApplication application = await activeDirectoryClient.Applications.GetByObjectId(RoleModel.ApplicationID).ExecuteAsync();
AppRole NewRole = new AppRole
{
    Id = CurrentRoleID,
    IsEnabled = true,
    AllowedMemberTypes = new List<string> { "User" },
    Description = RoleModel.RoleDescription,
    DisplayName = RoleModel.RoleName,
    Value = RoleModel.RoleName
 };
 application.AppRoles.Add(NewRole as AppRole);
 await application.UpdateAsync();

I also granted All Application Permissions not the Delegated Permissions from Azure portal to Microsoft Graph API. But i'm getting this error:

{"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."},"requestId":"e4187318-4b72-49fb-903d-42d419b65778","date":"2019-02-21T13:45:23"}}

Note: I'm able to create new user and updated a user using this access token though.

For Testing: For testing purpose, I granted Delegated Permissions to application and use client credential flow to get access token of current logged-in user and if the signed in user had enough directory role he/she can created role in application this is working fine.

Question: So, is it possible to create a new role in application using application credential flow? if so, am i missing something?

Updated: Added all Application Permission for API Windows Azure Active Directory and Grant admin consent.

enter image description here

Access Token: Access Token returned from ADzure AD

enter image description here

Upvotes: 2

Views: 657

Answers (1)

Rohit Saigal
Rohit Saigal

Reputation: 9664

Question: So, is it possible to create a new role in application using application credential flow? if so, am i missing something?

Answer to your general question is Yes, you can add a new role to application's roles using Azure AD Graph API and client credentials flow.

Working Code

Given below is the working code (it's a quick and dirty console application, just to make sure I test it before confirming)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace AddAzureADApplicationRoles
{
    class Program
    {
        static void Main(string[] args)
        {
            ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri("https://graph.windows.net/{myTenantId}"),
                async () => await GetTokenForApplication());

            //Fetch application Data from azure AD
            IApplication application = activeDirectoryClient.Applications.GetByObjectId("{MyAppObjectId}").ExecuteAsync().GetAwaiter().GetResult();

            AppRole NewRole = new AppRole
            {
                Id = Guid.NewGuid(),
                IsEnabled = true,
                AllowedMemberTypes = new List<string> {"User"},
                Description = "My Role Description..",
                DisplayName = "My Custom Role",
                Value = "MyCustomRole"
            };

            application.AppRoles.Add(NewRole as AppRole);
            application.UpdateAsync().GetAwaiter().GetResult();
        }

        public static async Task<string> GetTokenForApplication()
        {
            string TokenForApplication = "";

                AuthenticationContext authenticationContext = new AuthenticationContext(
                    "https://login.microsoftonline.com/{MyTenantId}",
                    false);

                // Configuration for OAuth client credentials 

                    ClientCredential clientCred = new ClientCredential("{AppId}",
                        "{AppSecret}"
                        );
                    AuthenticationResult authenticationResult =
                        await authenticationContext.AcquireTokenAsync("https://graph.windows.net", clientCred);
                    TokenForApplication = authenticationResult.AccessToken;                

            return TokenForApplication;
        }
    }
}

Probable Issue behind your specific exception

I think you have given application permissions on Microsoft Graph API, instead of permissions required for Azure AD Graph API.

While setting required permissions for your application, in Select an API dialog, make sure you select "Windows Azure Active Directory" and not "Microsoft Graph". I am giving screenshot for more detail next.

Steps to give required permissions

Notice that my app doesn't require any permissions on "Microsoft Graph API". It only has application permissions given for "Windows Azure Active Directory".

So, choose the appropriate application permission for your requirement, and make sure you do "Grant Permissions" at the end to provide Admin consent, as all the application permissions here mention Requires Admin as Yes.

enter image description here

On a side note, when you first create an app registration, it already has one delegated permission on Windows Azure Active Directory, so you may not need to explicitly select Windows Azure Active Directory again (unless you've removed it for your app), but just select the correct application permissions and do Grant Permissions as an administrator.

Upvotes: 1

Related Questions