AudienceUriValidationFailedException while downloading the sharepoint file
Praveen
0
Reputation points
Hi,
I am trying to download a file in python from sharepoint using python msal rest API. I am running the following code:
import msal
client_id = 'xxxx'
client_secret = 'yyyy'
tenant_id = 'zzzz'
authority = f"https://login.microsoftonline.com/{tenant_id}"
scope = ["https://graph.microsoft.com/.default"]
#scope = ["https://myorganization.sharepoint.com/.default"]
app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
result = app.acquire_token_for_client(scopes=scope)
if "access_token" in result:
access_token = result['access_token']
else:
print("Error acquiring token:", result.get("error"), result.get("error_description"))
import requests
print(access_token)
# SharePoint site and file details
sharepoint_site = "https://myorganization.sharepoint.com/sites/mysite"
file_path = "/Documents/myfile.xlsx" # Path to the file in SharePoint
# Construct the URL to the file
file_url = f"{sharepoint_site}/_api/web/getfilebyserverrelativeurl('{file_path}')/$value"
# Set up the request headers with the access token
headers = {
"Authorization": f"Bearer {access_token}"
}
# Make the request to download the file
response = requests.get(file_url, headers=headers)
if response.status_code == 200:
with open("downloaded_file.txt", "wb") as file:
file.write(response.content)
print("File downloaded successfully")
else:
print("Error downloading file:", response.status_code, response.text)
I am getting the following error:
Error downloading file: 401 {"error_description":"Exception of type 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException' was thrown."}
I am getting the token correctly but it fails while sending the request for download.
As far my understanding, I have given all the required permissions in the AAD portal. Am I missing something or any other permissions are required? Please help.
Thanks