Will
Will

Reputation: 2410

Calling MS Graph with delegated privileges doesn't work while application privileges do

I try to get a user's custom attribute using a graph api call :

I have setup an app registration with User.ReadWrite.All Delegated privileges as stated in the documentation and Granted admin privileges:

enter image description here

Using python, I can fetch a token using my app registration secret :

def retrieve_token(endpoint, client_id, client_secret):
    # endpoint = "https://login.microsoftonline.com/<tenant-id>/oauth2/token"
    payload = {
        "grant_type":"client_credentials",
        "client_id": client_id,
        "client_secret": client_secret,
        "resource":"https://graph.microsoft.com"
    }
    r = requests.request("POST", endpoint,data=payload).json()["access_token"]
    return r # returns a valid jwt token

Using that token I then call a function to get my user's attributes :

def get_user_role(endpoint,user_uid, token):
    # endpoint = "https://graph.microsoft.com/v1.0/users/"
    url = endpoint + user_uid 
    headers = {
        "Authorization": "Bearer " + token, 
        "Content-Type": "application/json"
    }
    return requests.request("GET", url, headers=headers).json()

For some reason, it lacks of privileges :

{'error': {'code': 'Authorization_RequestDenied', 'message': 'Insufficient privileges to complete the operation.', 'innerError': {'date': '2022-03-29T16:11:38', 'request-id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 'client-request-id': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'}}}

If I go back to my api's permissions and change the User.ReadWrite.All from Delegated permissions to Application permissions it works.

From what I read in this scenario I should use Delegated permission but how to get that to work?

Upvotes: 2

Views: 1486

Answers (1)

RahulKumarShaw
RahulKumarShaw

Reputation: 4602

If you are using the client credentials follow(Authenticating using Client ID and Client Secret) so you should require to Application permissions to get token and call a function to get my user's attributes. So it won't Possible to calling an API with Client Crendetial Token using delegated permissions.

  • As junnas stated in comment is correct You typically use delegated permissions when you want to call the Web API as the logged on user.

  • Application Permissions: Your application needs to access the web API directly as itself (no user context).

So you should change the way to get the access token use e.g. authorization code flow or device code flow to get an access token as a signed in user

You can refer this Document can help Desktop app that calls web APIs: Acquire a token using Username and Password

Upvotes: 3

Related Questions