我正在尝试使用 Python 中的 Microsoft 图形 API 导入数据。我不是 Python 开发人员,所以我无法这样做。我真的不知道如何使用 Secret_Key_Name 和 Secret_ID,但我猜它们充当用户名和密码。我在这方面特别需要帮助。当我只使用其余 3 个键时,我收到此错误。
API Request Error: 403-{"error":{"code":"Authorization_RequestDenied","message":"Insufficient privileges to complete the operation.","innerError":{"date":"2023-08-14T13:31:49","request-id":"[Request ID]","client-request-id":"[Client Request ID]"}}}
Python代码:
import requests
import msal
client_id = "[Client ID API Key]"
client_secret = "[Client Secret API key]"
tenant_id = "[Tenant ID API Key]"
secret_key_name = "[Secret key Name]"
Secret_ID = "[Secret ID]"
authority = f'https://login.microsoftonline.com/{tenant_id}'
app = msal.ConfidentialClientApplication(
client_id = client_id,
client_credential = client_secret,
authority = authority
)
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(scopes = ['https://graph.microsoft.com/.default'])
else:
result = None
if not result:
result = app.acquire_token_for_client(scopes = ['https://graph.microsoft.com/.default'])
if 'access_token' in result:
access_token = result['access_token']
headers = {
'Authorization' : f'Bearer {access_token}',
'Content-Type' : 'application/json'
}
api_url = 'https://graph.microsoft.com/v1.0/users'
response = requests.get(api_url, headers = headers)
if response.status_code == 200:
user_data = response.json()
print(user_data)
else:
print(f"API Request Error: {response.status_code}-{response.content.decode('utf-8')}")
else:
print(f"Token Acquisition Error : {result.get('error')}-{result.get('error_description')}")
如果您错过添加所需的API,通常会出现此错误 权限或授予他们管理员同意。生成token无需添加secret ID和secret name。
我注册了一个 Azure AD 应用程序并在未经同意的情况下添加了 API 权限:
当我在我的环境中运行你的代码时,我也遇到了相同的错误,如下所示:
要解决错误,请确保授予管理员同意添加的权限:
当我在授予管理员同意后再次运行相同的代码时,我成功地获得了响应,用户数据如下:
import requests
import msal
client_id = "appId"
client_secret = "secret"
tenant_id = "tenantId"
#secret_key_name = "[Secret key Name]"
#Secret_ID = "[Secret ID]"
authority = f'https://login.microsoftonline.com/{tenant_id}'
app = msal.ConfidentialClientApplication(
client_id = client_id,
client_credential = client_secret,
authority = authority
)
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(scopes = ['https://graph.microsoft.com/.default'])
else:
result = None
if not result:
result = app.acquire_token_for_client(scopes = ['https://graph.microsoft.com/.default'])
if 'access_token' in result:
access_token = result['access_token']
headers = {
'Authorization' : f'Bearer {access_token}',
'Content-Type' : 'application/json'
}
api_url = 'https://graph.microsoft.com/v1.0/users'
response = requests.get(api_url, headers = headers)
if response.status_code == 200:
user_data = response.json()
print(user_data)
else:
print(f"API Request Error: {response.status_code}-{response.content.decode('utf-8')}")
else:
print(f"Token Acquisition Error : {result.get('error')}-{result.get('error_description')}")
回复: