使用Python调用Microsoft Graph API遇权限不足,需密钥使用指导
问题解决:Python调用Microsoft Graph API的密钥疑惑与403权限错误
一、Secret_Key_Name和Secret_ID的作用说明
你代码里定义的secret_key_name和Secret_ID两个变量在当前的认证流程中完全不需要,可以直接删除。
当前你使用的是客户端凭据流(通过client_id+client_secret获取token),这种认证方式只需要tenant_id、client_id、client_secret三个参数即可完成token获取。你提到的这两个密钥可能是混淆了其他认证场景(比如使用Azure密钥保管库存储密钥、或者证书认证),但在当前代码逻辑里它们没有任何作用。
二、403权限不足错误的解决方法
出现Authorization_RequestDenied错误的核心原因是你的Azure应用注册没有被授予访问Microsoft Graph /users接口的权限,具体修复步骤如下:
- 登录Azure门户,找到你的应用注册
- 进入API权限页面,点击添加权限
- 选择Microsoft Graph,然后选择应用权限(注意:客户端凭据流只能使用应用权限,不能用委托权限)
- 搜索并添加
User.Read.All权限(如果需要读取所有用户信息),或者根据你的实际需求选择对应权限 - 点击授予管理员同意(必须由租户管理员操作,否则权限不会生效)
三、优化后的代码(删除无用变量)
import requests import msal client_id = "[Client ID API Key]" client_secret = "[Client Secret API key]" tenant_id = "[Tenant ID API Key]" 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')}")
内容的提问来源于stack exchange,提问作者Dhiraj D
相关产品推荐
相关产品推荐

