我使用 python 获取 Dynamics 365 Marketing 的访问令牌。这是在我们公司迁移新策略以在 Microsoft 帐户上启用 MFA 之前为我工作的代码,因此我们需要批准从我们的设备登录并输入号码以批准从我们的手机登录。
import adal
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
token_response = auth_context.acquire_token_with_username_password(https://xxxx.xxx.dynamics.com/", username, password, client_id)
Access_Token = token_response["accessToken"]
但是,当我现在运行它时,我收到错误
"AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access"
。另外,我没有任何管理员权限来更改 azure 门户中的任何内容,并且我没有客户端密钥,并且无法从 IT 团队获取它,因为他们不提供该密钥。在这种情况下如何在没有客户端密钥的情况下获取访问令牌?
如本MS 文档中所述,
如果用户需要使用多重身份验证(MFA)来登录应用程序,则在使用用户名密码流生成令牌时,他们将被阻止。
最初。当我尝试使用用户名密码流程为启用了 MFA 的用户生成令牌时,我也遇到了同样的错误:
import adal
auth_context = adal.AuthenticationContext("https://login.microsoftonline.com/common")
username = "[email protected]"
password = "xxxxxxxx"
client_id = "appId"
try:
token_response = auth_context.acquire_token_with_username_password("https://xxxxx.xxxxx.crm.dynamics.com/", username, password, client_id)
access_token = token_response["accessToken"]
print("Access token acquired successfully:", access_token)
except adal.AdalError as e:
print(e.error_response)
回复:
要解决该错误,您需要切换到交互式流程或设备代码流程,其中涉及用户至少登录一次以完成 MFA。
要使用交互流获取令牌,您需要在移动和桌面应用程序平台中添加重定向URI为http://localhost。由于您无权更改 Portal 中的任何内容,因此您可以使用设备代码流程。
您可以利用以下示例Python代码通过设备代码流程获取令牌:
import adal
authority_url = "https://login.microsoftonline.com/common"
client_id = "appId"
auth_context = adal.AuthenticationContext(authority_url)
# Initiate device code flow
device_code = auth_context.acquire_user_code("https://xxxx.xxxxx.xxx.dynamics.com/", client_id)
print(device_code['message'])
# Poll for token using device code
token_response = auth_context.acquire_token_with_device_code("https://xxxx.xxxxx.xxx.dynamics.com/", device_code, client_id)
access_token = token_response["accessToken"]
print("Access token acquired successfully:", access_token)
当您运行代码示例时,它将显示一条带有链接和设备代码的消息,如下所示:
单击链接将打开浏览器并要求您输入设备代码,如下所示:
在
Next
步骤中,它会要求您使用Azure帐户登录,其中涉及MFA提示,如下所示:
认证成功后,会显示如下画面:
当您现在检查输出控制台时,访问令牌将成功生成,如下所示: