我目前正在使用Python开发Azure Web App,它使用Azure AD身份验证进行网站访问。我想显示当前用户的电子邮件(我计划稍后使用此访问层也)。我看到了一种通过使用委托的GraphAPI来获取用户详细信息的方法。我尝试了下面的方法:
authority = f'https://login.microsoftonline.com/{subid}'
scope = ["https://graph.microsoft.com/.default"]
app = ConfidentialClientApplication(
client_id,
authority=authority,
client_credential=client_secret
)
token_response = app.acquire_token_for_client(scopes=scope)
access_token = token_response['access_token']
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
user_data = response.json()
print("~~~~~~~~~~~~~~~~~~~~~~")
for key, value in user_data.items():
print(f'{key}: {value}')
print("~~~~~~~~~~~~~~~~~~~~~~")
但这会返回错误:
error: {'code': 'BadRequest', 'message': '/me request is only valid with delegated authentication flow.', 'innerError': {'date': '2023-10-20T13:05:47', 'request-id': '9b6d8130-5bf6-4711-ba90-14ccaef0b127', 'client-request-id': '9b6d8130-5bf6-4711-ba90-14ccaef0b127'}}
我假设委托将工作作为用户需要签署并在azure上进行身份验证才能访问该网站,或者我错过了什么?
任何帮助或替代方法将不胜感激
1条答案
按热度按时间svmlkihl1#
发生错误的原因是您的代码使用客户端凭据流来生成访问令牌以调用**
/me
端点,这不是委派流,因为它不涉及用户交互。当我在我的环境中运行你的代码时,我也得到了相同的错误**如下:
回复:
要解决错误,需要切换到授权码流、交互流等委托流。需要用户登录才能生成访问令牌。
在我的例子中,我使用了interactive flowbyenablingbelow选项,并在移动的/桌面平台中添加了http://localhost作为redirect URI:
当我运行下面修改过的python代码时,它要求我选择一个帐户来登录:
登录时,用户将获得同意屏幕以接受以下权限:
接受同意后,我在输出控制台成功得到了带有登录用户详细信息的响应,如下所示: