我正在尝试使用在 Microsoft 的帮助下获得的令牌在 Python 中创建一个脚本:https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2 -client-creds-grant-flow#get-a-token,允许我在 Azure 门户中进行身份验证,并能够进行 GET 调用来获取一个或多个用户的信息。
我可以通过仅提供租户、
client_id
和client_secret
的脚本获取令牌,但是当我使用令牌调用 API 时,出现错误。这是一段代码,只是函数,它为我提供了 .json 和我需要的信息:
def call_api_with_token(token, subscription_id, resource_group_name, service_name, user_id):
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.ApiManagement/service/{service_name}/users/{user_id}?api-version=2022-08-01"
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to call API: {response.text}")
我收到此错误:
Error: {"error":{"code":"Authorization_RequestDenied","message":"Insufficient privileges to complete the operation.","innerError":{"date":"2024-04-01T14:40:30","request id":"xxxx","client-request-id":"xxx"}}}
我尝试了其他脚本,看过视频,但一次又一次地出现此错误。是否可能是因为我确实需要申请任何警察或通过令牌更改此访问的任何 API 权限?
要将 Azure 管理 API 作为服务主体调用,请确保在所需的 Azure 资源下为其分配正确的 RBAC 角色。
我注册了一个 Azure AD 应用程序,并通过授予同意添加了 API 权限:
就我而言,我在 Azure APIM 资源下向上述服务主体添加了 Reader 角色,如下所示:
为了通过调用 Azure 管理 API 来获取用户,我使用了以下代码并成功获得了响应:
import requests
def get_access_token(tenant_id, client_id, client_secret):
token_url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://management.azure.com/.default'
}
response = requests.post(token_url, data=data)
if response.status_code == 200:
return response.json()['access_token']
else:
raise Exception(f"Failed to obtain access token: {response.text}")
def call_api_with_token(token, subscription_id, resource_group_name, service_name, user_id):
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.ApiManagement/service/{service_name}/users/{user_id}?api-version=2022-08-01"
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Failed to call API: {response.text}")
def main():
# Replace placeholders with your actual values
tenant_id = 'tenantId'
client_id = 'appId'
client_secret = 'secret'
subscription_id = 'subId'
resource_group_name = 'Sri'
service_name = 'DemoAPIM0304'
user_id = 'ID0304'
token = get_access_token(tenant_id, client_id, client_secret)
user_info = call_api_with_token(token, subscription_id, resource_group_name, service_name, user_id)
print("User Information:", user_info)
if __name__ == "__main__":
main()
回复: