我正在使用访问令牌浏览共享点上的文件。但是,我认为我也可以使用它来读取文件的内容,但我遇到了以下错误。有谁知道我该如何解决这个问题?
{“error_description”:“类型>'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException'的异常是 抛出。”}
# Define imports
import requests
import pathlib
# Copy access_token and specify the MS Graph API endpoint you want to call, e.g. 'https://graph.microsoft.com/v1.0/groups' to get all groups in your organization
#access_token = '{ACCESS TOKEN YOU ACQUIRED PREVIOUSLY}'
url = "https://graph.microsoft.com/v1.0/..../search(q='593218')/"
headers = {
'Authorization': token_result['access_token']
}
consentfilecount=0
clientreportcount = 0
graphlinkcount = 0
while True:
try:
graph_result = requests.get(url=url, headers=headers)
graph_result.raise_for_status()
except:
token_result = client.acquire_token_for_client(scopes=scope)
headers = {
'Authorization': token_result['access_token']
}
if ('value' in graph_result.json()):
for list in graph_result.json()['value']:
for ele in finalReportNames:
if ele.lower() in list["name"].lower():
clientreportcount +=1
#below does not work
response = requests.get(list["webUrl"],headers={"Authorization": token_result['access_token']})
print(response)
print(list["name"])
print(list["webUrl"])
print(pathlib.Path(list["name"]).suffix)
#print(graph_result.json())
if('@odata.nextLink' in graph_result.json()):
url = graph_result.json()['@odata.nextLink']
graphlinkcount += 1
else:
break
print(consentfilecount)
如果访问令牌受众与请求不匹配或受众不是预期值,通常会出现错误 “Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException”。
当您使用 Microsoft Graph API 查询访问 SharePoint 文件时,您必须生成并传递 Microsoft Graph 访问令牌。
在 Azure AD 应用程序中添加 Microsoft Graph API 应用程序权限:
因此,通过使用以下代码片段生成令牌来修改您的代码:
from msal import ConfidentialClientApplication
import requests
# Set the values for your application
client_id = 'ClientID'
client_secret = 'ClientSecret'
tenant_id = 'TenantID'
scope = ['https://graph.microsoft.com/.default']
# Create a ConfidentialClientApplication object
app = ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority='https://login.microsoftonline.com/' + tenant_id
)
# Acquire a token for the client
token_result = app.acquire_token_for_client(scopes=scope)
# Get the access token from the token result
access_token = token_result['access_token']
print(access_token)
确保在解码访问令牌时,aud必须是
https://graph.microsoft.com
如果您想使用 SharePoint Rest API 查询进行查询,则通过将范围传递为
https://microsoft.sharepoint.com/.default
来生成令牌
要搜索文件,请参阅使用 Microsoft 搜索 API 搜索 OneDrive 和 SharePoint 内容 - Microsoft Graph |微软
获取文件内容,请参阅下载文件 - Microsoft Graph v1.0 |微软