1
votes

I am creating a C# Console Application that is reading and creating Azure AD accounts for a specific tenant. I have added a Azure AD application and noted the AppId, AppKey (secret), TenantId, TenantName.

For this to work, we utilize the following NuGet packages :

Reading the Azure AD accounts from the domain works correctly, but creating a new Azure AD account throws an exception : activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();

"Insufficient privileges to complete the operation." "{\"odata.error\":{\"code\":\"Authorization_RequestDenied\",\"message\":{\"lang\":\"en\",\"value\":\"Insufficient privileges to complete the operation.\"}}}" at System.Data.Services.Client.SaveResult.HandleResponse() at System.Data.Services.Client.BaseSaveResult.EndRequest() at System.Data.Services.Client.DataServiceContext.EndSaveChanges(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.ActiveDirectory.GraphClient.Extensions.DataServiceContextWrapper.d__74.MoveNext()

The authentication is performed by using the AppId & Secret because the Console application doesn't have UI.

public async Task<string> AcquireTokenAsyncForApplication()
{
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenantName, false);
// Config for OAuth client credentials 
ClientCredential clientCred = new ClientCredential("<appid>", "<appsecret>");
var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.windows.net", clientCred);
authenticationResult.Wait();            

return authenticationResult.Result.AccessToken;
}

public void Authenticate()
{
Uri servicePointUri = new Uri("https://graph.windows.net");
Uri serviceRoot = new Uri(servicePointUri, tenantId);
activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await AcquireTokenAsyncForApplication());
}

I enabled all permittions on the application itself and delegated permittions , but the authorization exception continues to appear. How can I find the error here? How can I solve this issue?

Best regards, Jens

1

1 Answers

2
votes

To create users via Azure Graph REST using the client credential, we can config the Directory.ReadWrite.All permssion for the application permission like figure below: enter image description here

After you acquire the access token, you can parse the token from here and ensure that the Directory.ReadWrite.All is in the token before you create a user.