I am working on an API that will download the videos from OneDrive by providing a URI.
I was able to get the access token but when I try to download the file I get an error stating:
/me request is only valid with delegated authentication flow.
Below is the code that I used.
I got the access token using this API-
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
# Fetch the access token
token = oauth.fetch_token(
token_url=token_url,
client_id=client_id,
client_secret=client_secret,
scope=scope
)
# Print the access token
print(token['access_token'])`
This worked fine.
then I called this api to fetch file details-
`file_url = 'onedrive file url'
# Set the API endpoint and parameters
url = f'https://graph.microsoft.com/v1.0/me/drive/root:/Documents/{file_url}:/'
headers = {
'Authorization': f'Bearer {access_token}'
}
# Make the API request to get the file metadata
response = requests.get(url, headers=headers)
# Check if the request was successful
if response.status_code == 200:
# Get the file ID and name from the metadata
file_id = response.json()['id']
file_name = response.json()['name']
print(f'File ID: {file_id}, File Name: {file_name}')
# Download the file content
download_url = f'https://graph.microsoft.com/v1.0/me/drive/items/{file_id}/content'
response = requests.get(download_url, headers=headers)
# Check if the download was successful
if response.status_code == 200:
# Write the file to disk
with open(file_name, 'wb') as f:
f.write(response.content)
print(f'{file_name} has been downloaded.')
else:
print(f'Error downloading {file_name}: {response.text}')
else:
print(f'Error getting metadata for {file_url}: {response.text}')`
This returns the error:
{
"error": {
"code": "BadRequest",
"message": "/me request is only valid with delegated authentication flow.",
"innerError": {
"date": "2023-03-27T21:15:20",
"request-id": "d2f3f66b-7bc8-4806-a082-f2d763482570",
"client-request-id": "d2f3f66b-7bc8-4806-a082-f2d763482570"
}
}
}
any ideas?
You cannot use the /me
path segment using an app-only token (i.e. the Client_Credentials OAuth flow).
The /me
segment is an alias for /users/{current user id}
. When you authenticate using Client Credentials, you are authenticating as an Application rather than on-behalf of a given User. Without a User, there is no way for Graph to determine which User in AAD /me
should map to.
You will either need to explicitly reference the User (/users/{id}
) or switch to using an Authorization Code flow. This OAuth flow will generate a token on behalf of the authenticated User and enable the /me
segment.