你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Python 的 Microsoft 身份验证库 (MSAL)

开始使用适用于 Python 的 Microsoft 身份验证库,使用 Microsoft 标识 (Azure ADMicrosoft 帐户Azure AD B2C 帐户登录用户或应用,) 并获取令牌以调用 Microsoft API(如 Microsoft Graph)或向Microsoft 标识平台注册的自己的 API。

请按照步骤操作,安装程序包并试用基本任务的示例代码。

快速入门 | API 参考文档 | 样品

先决条件

安装包

安装 MSAL for Python 包。 可以在 Pypi 上找到 MSAL Python。

pip install msal

设置

在使用 MSAL Python 之前,请将应用程序注册到 Microsoft 标识平台。

使用情况

使用 MSAL Python 获取令牌遵循此 3 步模式。 这是高级概念模式。 对于不同的流,会有一些变化。 这些示例在 可运行示例中进行了演示。

  1. MSAL 建议在 公共客户端应用程序和机密客户端应用程序之间完全分离。 因此,请创建 PublicClientApplicationConfidentialClientApplication 实例,并在应用的生命周期内重复使用它。 以下示例演示 PublicClientApplication

    from msal import PublicClientApplication
    app = PublicClientApplication(
        "your_client_id",
        authority="https://login.microsoftonline.com/Enter_the_Tenant_Name_Here")
    

    稍后,每次需要访问令牌时,首先需要:

    result = None  # It is just an initial value. Please follow instructions below.
    
  2. MSAL 中的 API 模型提供有关如何使用令牌缓存的显式控制。 此缓存部分在技术上是可选的,但我们强烈建议你利用 MSAL 缓存的强大功能。 它将自动为你处理令牌刷新。

    # We now check the cache to see
    # whether we already have some accounts that the end user already used to sign in before.
    accounts = app.get_accounts()
    if accounts:
        # If so, you could then somehow display these accounts and let end user choose
        print("Pick the account you want to use to proceed:")
        for a in accounts:
            print(a["username"])
        # Assuming the end user chose this one
        chosen = accounts[0]
        # Now let's try to find a token in cache for this account
        result = app.acquire_token_silent(["your_scope"], account=chosen)
    
  3. 如果缓存中没有合适的令牌,或者已选择跳过上一步,请向 Azure AD 发送请求以获取令牌。 根据客户端类型和方案,有不同的方法。 此处我们演示占位符流。

    if not result:
        # So no suitable token exists in cache. Let's get a new one from Azure AD.
        result = app.acquire_token_by_one_of_the_actual_method(..., scopes=["User.Read"])
    if "access_token" in result:
        print(result["access_token"])  # Yay!
    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))  # You may need this when reporting a bug
    

有关 MSAL Python 功能和用法的更多详细信息,请参阅 GitHub 上的 Wiki

从 ADAL 迁移到 MSAL

如果应用程序使用 ADAL Python,建议将其更新为使用 MSAL Python。 ADAL Python 中不会执行任何新功能工作。

请参阅 ADAL 到 MSAL 迁移 指南。

后续步骤