快速入门:使用应用的标识获取令牌并从 Python 控制台应用中调用 Microsoft Graph APIQuickstart: Acquire a token and call Microsoft Graph API from a Python console app using app's identity

在本快速入门中,首先编写 Python 应用程序,该应用程序使用其标识获取访问令牌,然后调用 Microsoft Graph API,以便在目录中显示用户列表In this quickstart, write a Python application that gets an accessing token using the app's identity, and then calls the Microsoft Graph API to display a list of users in the directory. 此方案适用于无外设且无人参与的作业或 Windows 服务需要使用应用程序标识而非用户标识运行的情况。This scenario is useful for situations where headless, unattended job or a windows service needs to run with an application identity, instead of a user's identity.

显示本快速入门生成的示例应用的工作原理Shows how the sample app generated by this quickstart works

先决条件Prerequisites

若要运行此示例,需要:To run this sample, you need:

注册并下载快速入门应用Register and download your quickstart app

可以使用两个选项来启动快速入门应用程序:“快速”(下面的选项 1)和“手动”(选项 2)You have two options to start your quickstart application: Express (Option 1 below), and Manual (Option 2)

选项 1:注册并自动配置应用,然后下载代码示例Option 1: Register and auto configure your app and then download your code sample

  1. 转到新的 Azure 门户 - 应用注册窗格。Go to the new Azure portal - App registrations pane.
  2. 输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
  3. 遵照说明下载内容,并只需单击一下自动配置新应用程序。Follow the instructions to download and automatically configure your new application with just one click.

选项 2:注册并手动配置应用程序和代码示例Option 2: Register and manually configure your application and code sample

步骤 1:注册应用程序Step 1: Register your application

若要手动注册应用程序并将应用的注册信息添加到解决方案,请执行以下步骤:To register your application and add the app's registration information to your solution manually, follow these steps:

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal using a work or school account.
  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户。If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant.
  3. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.
  4. 选择“新注册”。Select New registration.
  5. 出现“注册应用程序”页后,请输入应用程序的注册信息。When the Register an application page appears, enter your application's registration information.
  6. 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 Daemon-console,然后选择“注册”以创建应用程序。In the Name section, enter a meaningful application name that will be displayed to users of the app, for example Daemon-console, then select Register to create the application.
  7. 注册以后,选择“证书和机密”菜单。Once registered, select the Certificates & secrets menu.
  8. 在“客户端机密”下,选择“+ 新建客户端机密”。 Under Client secrets, select + New client secret. 为它提供一个名称,然后选择“添加”。Give it a name and select Add. 将机密复制到安全位置。Copy the secret on a safe location. 稍后需要在代码中使用它。You will need it to use in your code.
  9. 现在请依次选择“API 权限”菜单、“+ 添加权限”按钮、“Microsoft Graph”。 Now, select the API Permissions menu, select + Add a permission button, select Microsoft Graph.
  10. 选择“应用程序权限”。Select Application permissions.
  11. 在“用户”节点下选择“User.Read.All”,然后选择“添加权限”。 Under User node, select User.Read.All, then select Add permissions

下载并配置快速入门应用Download and configure your quickstart app

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in Azure portal

为使本快速入门的代码示例正常运行,需创建客户端机密,并添加 Graph API 的 User.Read.All 应用程序权限。For the code sample for this quickstart to work, you need to create a client secret, and add Graph API's User.Read.All application permission.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载 Python 项目Step 2: Download your Python project

备注

Enter_the_Supported_Account_Info_Here

步骤 3:配置 Python 应用Step 3: Configure your Python project

  1. 将 zip 文件提取到靠近磁盘根目录的本地文件夹,例如 C:\Azure-SamplesExtract the zip file to a local folder close to the root of the disk, for example, C:\Azure-Samples.

  2. 导航到子文件夹“1-Call-MsGraph-WithSecret”。Navigate to the sub folder 1-Call-MsGraph-WithSecret".

  3. 编辑 parameters.json,将字段 authorityclient_idsecret 的值替换为以下代码片段:Edit parameters.json and replace the values of the fields authority, client_id, and secret with the following snippet:

    "authority": "https://login.partner.microsoftonline.cn/Enter_the_Tenant_Id_Here",
    "client_id": "Enter_the_Application_Id_Here",
    "secret": "Enter_the_Client_Secret_Here"
    

    其中:Where:

    • Enter_the_Application_Id_Here - 是已注册应用程序的应用程序(客户端)IDEnter_the_Application_Id_Here - is the Application (client) ID for the application you registered.
    • Enter_the_Tenant_Id_Here - 将此值替换为租户 ID租户名称(例如 contoso.microsoft.com)Enter_the_Tenant_Id_Here - replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
    • Enter_the_Client_Secret_Here - 将此值替换为在步骤 1 中创建的客户端机密。Enter_the_Client_Secret_Here - replace this value with the client secret created on step 1.

提示

若要查找“应用程序(客户端) ID”、“目录(租户) ID”的值,请转到 Azure 门户中应用的“概览”页。 To find the values of Application (client) ID, Directory (tenant) ID, go to the app's Overview page in the Azure portal. 若要生成新密钥,请转到“证书和机密”页。To generate a new key, go to Certificates & secrets page.

如果尝试在此时运行应用程序,则会收到“HTTP 403 - 禁止访问”错误:Insufficient privileges to complete the operationIf you try to run the application at this point, you'll receive HTTP 403 - Forbidden error: Insufficient privileges to complete the operation. 之所以出现这种错误,是因为任何仅限应用的权限都需要管理员许可:目录的全局管理员必须为应用程序授予许可。This error happens because any app-only permission requires Admin consent: a global administrator of your directory must give consent to your application. 根据自己的角色选择下面的一个选项:Select one of the options below depending on your role:

全局租户管理员Global tenant administrator

如果你是全局租户管理员,请转到 Azure 门户的应用程序注册(预览版)中的“API 权限”页,选择“为 {租户名称} 授予管理员许可”(其中,{租户名称} 是目录的名称)。If you are a global tenant administrator, go to API Permissions page in the Azure Portal's Application Registration (Preview) and select Grant admin consent for {Tenant Name} (Where {Tenant Name} is the name of your directory).

如果你是全局管理员,请转到“API 权限”页,选择“为 Enter_the_Tenant_Name_Here 授予管理员许可”If you are a global administrator, go to API Permissions page select Grant admin consent for Enter_the_Tenant_Name_Here

标准用户Standard user

如果你是租户的标准用户,则需请求全局管理员为你的应用程序授予管理员许可。If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. 为此,请将以下 URL 提供给管理员:To do this, give the following URL to your administrator:

https://login.partner.microsoftonline.cn/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here

其中:Where:

  • Enter_the_Tenant_Id_Here - 将此值替换为租户 ID租户名称(例如 contoso.microsoft.com)Enter_the_Tenant_Id_Here - replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
  • Enter_the_Application_Id_Here - 是已注册应用程序的应用程序(客户端)IDEnter_the_Application_Id_Here - is the Application (client) ID for the application you registered.

步骤 4:运行应用程序Step 4: Run the application

步骤 5:运行应用程序Step 5: Run the application

需要安装一次此示例的依赖项You'll need to install the dependencies of this sample once

pip install -r requirements.txt

然后,通过命令提示符或控制台运行应用程序:Then, run the application via command prompt or console:

python confidential_client_secret_sample.py parameters.json

你应该会在控制台输出上看到一些 Json 片段,表示 Azure AD 目录中的用户列表。You should see on the console output some Json fragment representing a list of users in your Azure AD directory.

重要

本快速入门应用程序使用客户端机密将自己标识为机密客户端。This quickstart application uses a client secret to identify itself as confidential client. 由于客户端机密是以纯文本形式添加到项目文件的,因此为了安全起见,建议在考虑将应用程序用作生产应用程序之前,使用证书来代替客户端机密。Because the client secret is added as a plain-text to your project files, for security reasons, it is recommended that you use a certificate instead of a client secret before considering the application as production application. 若要详细了解如何使用证书,请参阅有关此示例的这些说明它与本示例位于同一 GitHub 存储库中,但在另一个文件夹“2-Call-MsGraph-WithCertificate”中。For more information on how to use a certificate, see these instructions in the same GitHub repository for this sample, but in the second folder 2-Call-MsGraph-WithCertificate

详细信息More information

MSAL PythonMSAL Python

MSAL Python 是用于实现用户和(用于访问受 Microsoft 标识平台保护的 API 的)请求令牌登录的库。MSAL Python is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. 如前所述,本快速入门请求令牌的方法是使用应用程序自身的标识而不是委托的权限。As described, this quickstart requests tokens by using the application own identity instead of delegated permissions. 在此示例中使用的身份验证流称为客户端凭据 oauth 流The authentication flow used in this case is known as client credentials oauth flow. 若要详细了解如何搭配使用 MSAL Python 和守护程序应用,请参阅本文For more information on how to use MSAL Python with daemon apps, see this article.

运行以下 PIP 命令即可安装 MSAL Python。You can install MSAL Python by running the following pip command.

pip install msal

MSAL 初始化MSAL initialization

可以通过添加以下代码,为 MSAL 添加引用:You can add the reference for MSAL by adding the following code:

import msal

然后,使用以下代码对 MSAL 进行初始化:Then, initialize MSAL using the following code:

app = msal.ConfidentialClientApplication(
    config["client_id"], authority=config["authority"],
    client_credential=config["secret"])
其中:Where: 说明Description
config["secret"] 是在 Azure 门户中为应用程序创建的客户端机密。Is the client secret created for the application in Azure Portal.
config["client_id"] 是在 Azure 门户中注册的应用程序的应用程序(客户端) IDIs the Application (client) ID for the application registered in the Azure portal. 可以在 Azure 门户的应用的“概览”页中找到此值。You can find this value in the app's Overview page in the Azure portal.
config["authority"] 用户要进行身份验证的 STS 终结点。The STS endpoint for user to authenticate. 对于公有云,通常为 https://login.partner.microsoftonline.cn/{tenant},其中 {tenant} 是租户名称或租户 ID。Usually https://login.partner.microsoftonline.cn/{tenant} for public cloud, where {tenant} is the name of your tenant or your tenant Id.

有关详细信息,请参阅 ConfidentialClientApplication 的参考文档For more information, please see the reference documentation for ConfidentialClientApplication

请求令牌Requesting tokens

若要通过应用的标识来请求令牌,请使用 AcquireTokenForClient 方法:To request a token using app's identity, use AcquireTokenForClient method:

result = None
result = app.acquire_token_silent(config["scope"], account=None)

if not result:
    logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
    result = app.acquire_token_for_client(scopes=config["scope"])
其中:Where: 说明Description
config["scope"] 包含请求的范围。Contains the scopes requested. 对于机密客户端,这应该使用与 {Application ID URI}/.default 类似的格式,指示所请求的范围是在 Azure 门户的应用对象集中静态定义的范围(就 Microsoft Graph 来说,{Application ID URI} 指向 https://microsoftgraph.chinacloudapi.cn)。For confidential clients, this should use the format similar to {Application ID URI}/.default to indicate that the scopes being requested are the ones statically defined in the app object set in the Azure Portal (for Microsoft Graph, {Application ID URI} points to https://microsoftgraph.chinacloudapi.cn). 对于自定义 Web API,{Application ID URI} 是在 Azure 门户的应用程序注册(预览版)的“公开 API”部分中定义的。For custom web APIs, {Application ID URI} is defined under Expose an API section in Azure Portal's Application Registration (Preview).

有关详细信息,请参阅 AcquireTokenForClient 的参考文档For more information, please see the reference documentation for AcquireTokenForClient

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持If you need help, want to report an issue, or would like to learn about your support options, see Help and support for developers.

后续步骤Next steps

若要详细了解守护程序应用程序,请参阅方案登陆页To learn more about daemon applications, see the scenario landing page

有关守护程序应用程序教程,请参阅:For the daemon application tutorial, see:

了解有关权限和许可的详细信息:Learn more about permissions and consent:

若要详细了解此方案的身份验证流,请查看 Oauth 2.0 客户端凭据流:To know more about the auth flow for this scenario, see the Oauth 2.0 client credentials flow: