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?