你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 Python 的 Microsoft 身份验证库 (MSAL)
开始使用适用于 Python 的 Microsoft 身份验证库,使用 Microsoft 标识 (Azure AD、Microsoft 帐户和 Azure AD B2C 帐户登录用户或应用,) 并获取令牌以调用 Microsoft API(如 Microsoft Graph)或向Microsoft 标识平台注册的自己的 API。
请按照步骤操作,安装程序包并试用基本任务的示例代码。
先决条件
- 具有活动订阅的 Azure 帐户。 创建免费帐户。
- Python 3.6+。
安装包
安装 MSAL for Python 包。 可以在 Pypi 上找到 MSAL Python。
pip install msal
设置
在使用 MSAL Python 之前,请将应用程序注册到 Microsoft 标识平台。
使用情况
使用 MSAL Python 获取令牌遵循此 3 步模式。 这是高级概念模式。 对于不同的流,会有一些变化。 这些示例在 可运行示例中进行了演示。
MSAL 建议在 公共客户端应用程序和机密客户端应用程序之间完全分离。 因此,请创建
PublicClientApplication
或ConfidentialClientApplication
实例,并在应用的生命周期内重复使用它。 以下示例演示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.
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)
如果缓存中没有合适的令牌,或者已选择跳过上一步,请向 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 迁移 指南。
后续步骤
- 在 MSAL Python 中处理错误和异常:了解不同类型的错误以及如何处理常见登录错误。
- MSAL Python 中的日志记录:了解如何生成有助于诊断问题的日志消息。
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈