Error "Access token validation failure. Invalid audience." while using Microsoft Graph SDK

Nguyễn Gia bảo 20 Reputation points
2024-04-12T06:47:21.4533333+00:00

I'm trying to connect to Microsoft Graph API through Graph SDK to create mail using my organization domain. Here is my code:

import requests
import json
from urllib.parse import urlencode

client_id = "***"
client_secret = "***"
tenant_id = "***"

def get_access_token():
    url = "https://login.microsoftonline.com/{}/oauth2/token".format(tenant_id)
    payload = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret,
        "scope": "https://graph.microsoft.com/.default"
    }
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    response = requests.post(url, data=urlencode(payload), headers=headers)

    if response.status_code == 200:
        return response.json()["access_token"]
    else:
        raise Exception(f"Failed to get access token\n{response.text}")

def create_user(access_token, user_info):
    url = "https://graph.microsoft.com/v1.0/users"
    headers = {
        "Authorization": "Bearer {}".format(access_token),
        "Content-Type": "application/json"
    }
	
    data = {
        "accountEnabled": True,
        "displayName": user_info["name"],
        "mailNickname": user_info["email"],
        "userPrincipalName": f"{user_info['email'].split('@')[0]}@***",
        "passwordProfile": {
            "password": user_info["password"]
        }
    }

    response = requests.post(url, data=json.dumps(data), headers=headers)
    if response.status_code == 200:
        print(user_info["name"] + "@*** created successfully")
    else:
        raise Exception(f"Failed to create user {user_info['name']}\n{response.text}")


if __name__ == "__main__":
    with open("users.json") as f:
        users = json.load(f)
        access_token = get_access_token()
        for user in users:
            create_user(access_token, user)

I am getting the following error while executing the create_user() method: "code":"InvalidAuthenticationToken","message":"Access token validation failure. Invalid audience." It seems that my authProvider function returns a valid token. I have already set User.ReadWrite.All and Directory.ReadWrite.All in my code.

Can anyone help me resolve this issue?

Microsoft Security | Microsoft Graph
{count} votes

Accepted answer
  1. CarlZhao-MSFT 46,376 Reputation points
    2024-04-12T09:55:36.77+00:00

    Hi @Nguyễn Gia bảo

    The audience for your access token is a deprecated Azure AD Graph API, so it cannot be used to call the Graph API. When obtaining an access token, make sure that the value of the scope is: https://graph.microsoft.com/.default.


    If the reply helps, don't forget to accept it as an answer. Thanks!

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.