Python:MSAL --> 使用用户名和密码获取令牌

问题描述 投票:0回答:1

我正在按照 Microsoft 文档通过用户名和密码获取 MSAL 令牌

为了了解 MSAL 的工作原理,我尝试了一些非常简单的方法:使用用户名和密码获取令牌。下面示例中的大括号 ({}) 代表我复制到此处的 ID 或凭据。

authority_url = 'https://login.microsoftonline.com/{Tenant}’
app = msal.PublicClientApplication(
    authority=authority_url
    , client_id={client_id}'
    , client_credential=None
)

app.acquire_token_by_username_password(
    '{mail_of_windows_user}'
    , ‘{password_of_windows_user}’
    , scopes = ["User.Read"])

当我运行代码时,我收到 ID 为 7000218 的错误:

请求体必须包含以下参数: “client_assertion”或“client_secret”。

此错误是意外的,因为

PublicClientApplication
应该在没有客户端密钥的情况下工作。在参数 client_credential
文档
中,可以阅读:

对于 PublicClientApplication,您只需在此处使用 None 即可。

为什么我需要客户端密码,尽管文档表明我不需要客户端密码?

python authentication token msal
1个回答
0
投票

如果您在使用用户名密码流生成令牌时错过启用公共客户端流选项,通常会发生此错误,这是需要才能将应用程序注册识别为公共客户端应用程序。

最初,当我运行下面的代码来生成访问令牌而不启用公共客户端流选项时,我也遇到了相同的错误

import msal

authority_url ='https://login.microsoftonline.com/{Tenant}’
app = msal.PublicClientApplication(
    authority=authority_url,
    client_id={client_id},
    client_credential=None
)
result = app.acquire_token_by_username_password(
    '{mail_of_windows_user}'
    , '{password_of_windows_user}'
    , scopes = ["User.Read"])

if "access_token" in result:
    access_token = result["access_token"]
    print(f"Access Token: {access_token}")
else:
    print(result.get('error_description'))

回复:

enter image description here

要解决该错误,请确保在应用程序注册中启用公共客户端流选项,如下所示:

enter image description here

当我在启用公共客户端流后再次运行代码而不传递客户端密钥时,我成功获得了访问令牌作为响应:

import msal

authority_url ='https://login.microsoftonline.com/{Tenant}’
app = msal.PublicClientApplication(
    authority=authority_url,
    client_id={client_id},
    client_credential=None
)
result = app.acquire_token_by_username_password(
    '{mail_of_windows_user}'
    , '{password_of_windows_user}'
    , scopes = ["User.Read"])

if "access_token" in result:
    access_token = result["access_token"]
    print(f"Access Token: {access_token}")
else:
    print(result.get('error_description'))

回复:

enter image description here

您可以在 jwt.ms 中解码上述令牌并检查声明是否有效,如下所示:

enter image description here

参考: Microsoft 身份平台和 OAuth 2.0 资源所有者密码凭据

© www.soinside.com 2019 - 2024. All rights reserved.