Hi experts,
I've registered an APP on Azure and obtained a "client_id", a "tenant_id" and a "client_secret". Then I added to the "API Permissions" all the "Delegated" accesses to "Mail" and "Chat" since I want to API to interact with Outlook and Teams.
I'm using this code in Python to get the token.
from datetime import datetime
import requests
import msal
# Initialize the information for the API
client_id = "XXXX"
client_secret = "XXXX"
tenant_id = "XXXX"
authority = "https://login.microsoftonline.com/" + tenant_id
scope = ["https://outlook.office365.com/.default"]
user_principal_name = "******@XXXX.com"
# Create a confidential client application
app = msal.ConfidentialClientApplication(
client_id=client_id,
authority=authority,
client_credential=client_secret,
)
# Get a token for the app
result = app.acquire_token_for_client(scopes=scope)
result['access_token']
I'm able to generate a token but it doesn't contain the "scopes" I've added in the API Permissions.
My understanding is that "Scp" are required. Currently when trying to access the emails subject with this code:
if "access_token" in result:
# Define the endpoint URL
url = f"https://graph.microsoft.com/v1.0/users/{user_principal_name}/mailFolders/inbox/messages"
# Set up query parameters
today = datetime.now().isoformat(timespec='seconds')
subject_to_find = "test"
query_parameters = {
"$filter": f"receivedDateTime ge {today}Z and subject eq '{subject_to_find}'",
"$select": "subject",
}
# Set the headers
headers = {
'Authorization': 'Bearer ' + result['access_token'],
'Content-Type': 'application/json'
}
print(f"Headers: {headers}")
print(f"Query Parameters: {query_parameters}")
# Make the API request
response = requests.get(url, headers=headers, params=query_parameters)
# Check if the desired subject was found
if response.status_code == 200:
data = response.json()
if len(data["value"]) > 0:
print(True)
else:
print(False)
else:
print(f"API call failed with status code {response.status_code}. Response content: {response.content}")
else:
print(f"Could not acquire token: {result}")
But I got this error
API call failed with status code 401. Response content: b'{"error":{"code":"InvalidAuthenticationToken","message":"Access token validation failure. Invalid audience.","innerError":{"date":"2023-07-25T14:37:48","request-id":"6fc0cb65-694c-4fe4-9e18-fa36f2aca8e8","client-request-id":"6fc0cb65-694c-4fe4-9e18-fa36f2aca8e8"}}}'
Could you please let me know what I'm doing wrong and why the token doesn't reflect the access I granted to the API in the scopes?
Regards,
Dario