Недостаточно прав для завершения операции при импорте данных из API Microsoft Graph с помощью Python.
Я пытаюсь импортировать данные с помощью API графиков Microsoft в Python. Я не разработчик Python, поэтому не могу этого сделать. Я понятия не имею, как использовать Secret_Key_Name и Secret_ID, но предполагаю, что они действуют как имя пользователя и пароль. Мне особенно нужна помощь с этим. Когда я просто использую остальные три клавиши, я получаю эту ошибку.
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')}")
1 ответ
Ошибка обычно возникает, если вы пропустили добавление необходимых разрешений API или предоставление на них согласия администратора . Для создания токена нет необходимости добавлять секретный идентификатор и секретное имя.
Я зарегистрировал одно приложение 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')}")
Ответ: