Graph API - Insufficient privileges to complete the operation
Asked Answered
A

13

59

When trying to access the Graph Service Client using I am receiving the error:

Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.

After researching this error the most common solution was to set the permissions for the API. This had already been done and has permissions to read basic/full profiles.

I've delete and re-added the APIs.

Below is the code in my AzureAuthenticationProvider class which inherits from IAuthenticationProvider:

public class AzureAuthenticationProvider : IAuthenticationProvider
{
    private string _azureDomain = "myDevDom.onmicrosoft.com";

    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        try
        {
            string clientId = "2b823c67-1b0d-4a10-a9e1-737142516f5q";
            string clientSecret = "xxxxxx";

            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");

            ClientCredential credentials = new ClientCredential(clientId, clientSecret);

            AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);

            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
        }
        catch (Exception ex)
        {
        }
    }
}

I've tried changing the client secret to an invalid Id and it threw an error, so the client key is correct. I've also tried to verify that the access token is valid by altering the access token, this also returns a error.

The above code seems to work fine.

Below is the code where I'm trying to access Azure AD:

public async Task<IGraphServiceUsersCollectionPage> GetUsersByLastName(string lastname)  
{
    GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
    string filter = String.Format("startswith(surname, '{0}')", lastname);
    IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().Filter(filter).GetAsync(); //Fails on this line
    return users;
}

azureADpermissionProperties

Adoptive answered 2/6, 2017 at 7:49 Comment(7)
Which permissions have you added exactly? Could you post a screenshot? What you need is application permissions to read users.Stumpf
Thanks for the suggestion under the application permissions I've selected 'Read and write directory data' and under delegated permissions I have 'sign in and read user profile' 'real all users' basic profiles' and 'access the firectory as the signed-in user'. Although for testing in the dev application I have selected all available options and I'm still getting the authentication error.Adoptive
Delegated permissions don't matter for this API call. You are doing an app-only call (specifying a client id and secret). Have you also granted the permissions? You could check the access token contents in e.g. jwt.ioStumpf
@Stumpf I agree about the delegated permissions, I have set the application permission (for read and write directory data) above this - I've just cut the title out with the screenshot. When trying to grant permissions I get an error stating 'failed to grant permissions for application'. I'm guessing this could be the problem? Thanks for the help.Adoptive
Are you an admin in that Azure AD?Stumpf
@Stumpf .... no, currently testing this on a new Azure AD where I'm admin, how long do the permissions take to apply once saved in azure?Adoptive
It can take a couple minutes sometimes. Best way to know is to check the access token in jwt.io. Specifically, look at the scopes in the token. You should have something like Directory.ReadWrite.All in there.Stumpf
S
25

Please refer to below steps :

  1. From your screenshot , seems you grant Read and write directory data application permission for Windows Azure Active Directory(azure ad graph api) . Since you are using microsoft graph (https://graph.microsoft.com/) , you need to grant application permission for Microsoft Graph : enter image description here

  2. Since you are admin in your AAD, You could grant permission for users in organization by click Grant permission button shown in above screenshot .

  3. Then you could use your code (client credential flow to get the token) and query users information . If you check the claims in access token issued by azure ad , you could find Directory.Read.All permission in roles claim .

Sibylsibylla answered 2/6, 2017 at 9:51 Comment(1)
Thank you for your help. Sorry for the confusion with the screenshot, but I have actually granted permissions for Microsoft graph too. I think the problem might be that I'm not an admin, and although I have selected the permissions for the application, I am not able to grant permissions (I get an error stating 'failed to grant permissions for application'. I'm currently in the process of testing this where I'm an admin on azure AD. Thanks again for the suggestion.Adoptive
M
16

Grant permission Make sure click "Grant Permissions" and than Yes for all users accounts.

Midships answered 15/11, 2017 at 11:21 Comment(0)
S
15

In my case, delete user was not working. I took below steps & it started working for me.

Go to Azure Active Directory > Roles and administrators > Click on 'User administrator' > click on '+ Add assignment' to add your app. (i.e. console app using AAD Graph REST API to interact with Azure Active Directory).

Hope it helps someone.

Saponaceous answered 7/1, 2020 at 3:17 Comment(3)
That fixed it for me. I had Global Administrator which I thought would be enough, but needed to add User Administrator as well.Commute
Yes! I was wondering how to assign these permission to my app like I did know that set API permissions is not enough! Solved for me, thanks!Optimal
Nice! This worked perfectly for me! But the applications did not appear in the starting list under "all". I had to paste the Client ID of my application.Hanoverian
M
9

For me the key to solve this problem was hint:

To use the Graph API with your B2C tenant, you will need to register a dedicated application by using the generic App Registrations menu (All Services and there it is by default not Favourite starred) in the Azure Portal, NOT Azure AD B2C's Applications menu. You can't reuse the already-existing B2C applications that you registered in the Azure AD B2C's Applications menu.

Find more on page AD B2C API access demo

Maccabees answered 4/4, 2018 at 13:32 Comment(0)
I
3

In some cases the actual issue happens because we use "Application permissions" instead of "Delegated permissions". In my application, I have tried to list all the users with application permissions and it wasn't working. When I switched to a delegated permissions, it worked.

So, some quick check would be like this:

  1. Check if you are using Microsoft Graph API or something else
  2. Use Delegated permissions
  3. Click Grant permissions button to propagate permissions :)

Hopefully, this would help someone.

Inwrought answered 28/12, 2017 at 15:54 Comment(0)
A
2

Suppose you want to create group in azure active directory i have to performer the following steps to solve this problem

  1. AD > App Registered > your app
  2. Select Required Permission
  3. Click Add and select Microsoft Graph and add it
  4. select Microsoft Graph
  5. select Read and write all groups from delegated permission list
  6. And save it
  7. Select Windows Azure Active Directory and grant all application permission
  8. Save it
Aidaaidan answered 23/8, 2017 at 12:11 Comment(0)
C
2

Go to Azure Portal -> Active Directory -> App registrations -> Select Your Application -> API permissions

Now, Click on Add a permission and choose Microsoft Graph, select Application Permission and search for User.Read.All

Add these permissions to your application and it should work.

Corncrib answered 26/7, 2022 at 9:3 Comment(0)
U
2

This answer is for those who are directly trying to use API.

You will have to regenerate the access token once you have added the required permissions. I added the following permissions (might be more than we actually require but it works now). enter image description here

After adding the permissions, I generated a new access token using:

curl -X POST "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "client_id=535fb089-9ff3-47b6-9bfb-4f1264799865" \
     -d "scope=https%3A%2F%2Fgraph.microsoft.com%2F.default" \
     -d "client_secret=<your-client-secret>" \
     -d "grant_type=client_credentials"

And used it in the api like below:

curl -X GET "https://graph.microsoft.com/v1.0/users" \
     -H "Authorization: Bearer {access-token}"
Unbridled answered 24/4, 2023 at 23:7 Comment(1)
Regenerate Auth Token was the key for my issueSynaesthesia
E
1

Grant permissions by ticking 'Directory.Read.All/ Write' is not enough.

I run into the same issue. and solved by adding service principle to administrator role.

If you application is created recently, this can be done Azure AD Powershell.

$pricinple = Get-AzureADServicePrincipal || Where-Object {$_.DisplayName -eq 'youappname'}

 $role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}

Add-AzureADDirectoryRoleMember -ObjectId $role.ObjectId -RefObjectId $pricinple.ObjectId

for detail, see https://learn.microsoft.com/en-us/powershell/module/Azuread/Add-AzureADDirectoryRoleMember?view=azureadps-2.0

If you application was created long time ago, you will need to use MSOnline. see: https://learn.microsoft.com/en-us/powershell/module/msonline/Add-MsolRoleMember?view=azureadps-1.0

Easting answered 22/5, 2019 at 1:9 Comment(3)
you don't want to this - it's using a sledgehammer to drive a nail if you give it Global Admin rights just to read the usersClergy
While I agree with @Clergy this is actually the only way to make it work. And not mentioned anywhere I could find in Microsoft docs. Thanks LangyEviaevict
This is just FYI for later readers, but It's important to identify what exactly seems to need global admin. You may need GA to initially grant the application identity the appropriate rights to the users. After that, to simply read user properties, the app should not need GA. Even granting User Administrator is better, but that should be part of trying to troubleshoot the issue if the app isn't doing writes. GA is not needed for nearly all per-user management tasks. Certainly for none that I manage, incl user/mailbox/group creations, MFA/SSPR etc.Clergy
P
1

I am using Credentials flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow and my problem was setting Delegate Permissions instead of Application Permission.

I could not get a user because I wasn't using User.Read.All from Application Permissions https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http

Application User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All

Pinxit answered 19/3, 2021 at 11:2 Comment(0)
K
0

I had to add all "groups" (ID, Access, SAML) into the token. This can be configurated in the Azure Active Directory Token Configuration and checked via https://jwt.io/.

Kilimanjaro answered 27/10, 2021 at 16:43 Comment(0)
B
0

you should give Directory.Read role to the service principal in the AD page, not the app register page. enter image description here

enter image description here

by the way. I am use python sdk azure-graphrbac with serviceprincipal from msrestazure.azure_active_directory import ServicePrincipalCredentials

    credential = ServicePrincipalCredentials(ServicePrincipal_APP_ID,ServicePrincipal_SECRET_VALUE,tenant=ServicePrincipal_TENANT_ID,resource="https://graph.windows.net/")
    self.client=GraphRbacManagementClient(credential,TENANT_ID,base_url)
Bayadere answered 18/11, 2021 at 8:29 Comment(0)
D
0

You need to add a permission e.g. User.Read.All for the request to work.

And don't forget to grant the permission which is found next to + add a permission

enter image description here

enter image description here

enter image description here

Drysalter answered 9/7 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.