Azure Web App使用Azure身份验证来访问Web应用程序,如何使用此身份验证来显示访问应用程序的用户的电子邮件地址?

j2datikz  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(108)

我目前正在使用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上进行身份验证才能访问该网站,或者我错过了什么?
任何帮助或替代方法将不胜感激

svmlkihl

svmlkihl1#

发生错误的原因是您的代码使用客户端凭据流来生成访问令牌以调用**/me端点,这不是委派流,因为它不涉及用户交互。
当我在我的环境中运行你的代码时,我也得到了
相同的错误**如下:

import msal
import requests

authority = f'https://login.microsoftonline.com/tenantId'
scope = ["https://graph.microsoft.com/.default"]
client_id = "appId"
client_secret = "secret"

app = msal.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("~~~~~~~~~~~~~~~~~~~~~~")

回复:

解决错误,需要切换到授权码流、交互流等委托流。需要用户登录才能生成访问令牌。
在我的例子中,我使用了interactive flowbyenablingbelow选项,并在移动的/桌面平台中添加了http://localhost作为redirect URI

当我运行下面修改过的python代码时,它要求我选择一个帐户来登录:

import msal
import requests

authority = f'https://login.microsoftonline.com/tenantId'
scope = ["https://graph.microsoft.com/.default"]
client_id = "appId"

app = msal.PublicClientApplication(
    client_id,
    authority=authority,
)

token_response = app.acquire_token_interactive(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("~~~~~~~~~~~~~~~~~~~~~~")

登录时,用户将获得同意屏幕以接受以下权限:

接受同意后,我在输出控制台成功得到了带有登录用户详细信息的响应,如下所示:

相关问题