แก้ไข

แชร์ผ่าน


Quickstart: Acquire a token and call Microsoft Graph from a Python daemon app

In this quickstart, you download and run a code sample that demonstrates how a Python application can get an access token using the app's identity to call the Microsoft Graph API and display a list of users in the directory. The code sample demonstrates how an unattended job or Windows service can run with an application identity, instead of a user's identity.

Diagram showing how the sample app generated by this quickstart works.

Prerequisites

To run this sample, you need:

Register and download your quickstart app

Step 1: Register your application

Tip

Steps in this article might vary slightly based on the portal you start from.

To register your application and add the app's registration information to your solution manually, follow these steps:

  1. Sign in to the Microsoft Entra admin center.
  2. If you have access to multiple tenants, use the Settings icon in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
  3. Browse to Identity > Applications > App registrations, select New registration.
  4. Enter a Name for your application, for example Daemon-console. Users of your app might see this name, and you can change it later.
  5. Select Register.
  6. Under Manage, select Certificates & secrets.
  7. Under Client secrets, select New client secret, enter a name, and then select Add. Record the secret value in a safe location for use in a later step.
  8. Under Manage, select API Permissions > Add a permission. Select Microsoft Graph.
  9. Select Application permissions.
  10. Under User node, select User.Read.All, then select Add permissions.

Step 2: Download the Python project

Download the Python daemon project

Step 3: Configure the Python project

  1. Extract the zip file to a local folder close to the root of the disk, for example, C:\Azure-Samples.

  2. Navigate to the sub folder 1-Call-MsGraph-WithSecret.

  3. Edit parameters.json and replace the values of the fields authority, client_id, and secret with the following snippet:

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

    Where:

    • Enter_the_Application_Id_Here - is the Application (client) ID for the application you registered.
    • 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 - replace this value with the client secret created on step 1.

Tip

To find the values of Application (client) ID, Directory (tenant) ID, go to the app's Overview page in the Microsoft Entra admin center. To generate a new key, go to Certificates & secrets page.

Standard user

If you're a standard user of your tenant, ask a Global Administrator to grant admin consent for your application. To do this, give the following URL to your administrator:

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

Where:

  • 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 - is the Application (client) ID for the application you registered previously.

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

You should see on the console output some JSON fragment representing a list of users in your Microsoft Entra directory.

Important

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. 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 Python

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. The authentication flow used in this case is known as client credentials oauth flow. For more information on how to use MSAL Python with daemon apps, see this article.

You can install MSAL Python by running the following pip command.

pip install msal

MSAL initialization

You can add the reference for MSAL by adding the following code:

import 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"] Is the client secret created for the application in Microsoft Entra admin center.
config["client_id"] Is the Application (client) ID for the application registered in the Microsoft Entra admin center. You can find this value in the app's Overview page in the Microsoft Entra admin center.
config["authority"] The STS endpoint for user to authenticate. Usually https://login.microsoftonline.com/{tenant} for public cloud, where {tenant} is the name of your tenant or your tenant ID.

For more information, please see the reference documentation for ConfidentialClientApplication.

Requesting tokens

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. 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 Microsoft Entra admin center (for Microsoft Graph, {Application ID URI} points to https://graph.microsoft.com). For custom web APIs, {Application ID URI} is defined under the Expose an API section in App registrations in the Microsoft Entra admin center.

For more information, please see the reference documentation for AcquireTokenForClient.

Help and support

If you need help, want to report an issue, or want 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.