python-3.x 调用MS图形API时出现问题

okxuctiv  于 2023-03-31  发布在  Python
关注(0)|答案(1)|浏览(108)

我正在开发一个API,它将通过提供URI从OneDrive下载视频。
我能够获得访问令牌,但当我尝试下载文件时,我得到一个错误:
/me请求仅对委托的身份验证流有效。
下面是我使用的代码。
我用这个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}')`

这将返回错误:

{
    "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"
        }
    }
}

有什么想法吗?

dgtucam1

dgtucam11#

您不能使用/me路径段使用仅应用令牌(即Client_Credentials OAuth流)。
/me段是/users/{current user id}的别名。当您使用客户端凭据进行身份验证时,您是作为应用程序进行身份验证,而不是代表给定用户进行身份验证。如果没有用户,Graph无法确定AAD /me中的哪个用户应Map到。
您需要显式引用User(/users/{id})或切换到使用授权代码流。此OAuth流将代表已验证的User生成令牌并启用/me段。

相关问题