Quickstart: Acquire a token and call Microsoft Graph API from a Python console app using app's identity

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.

Shows how the sample app generated by this quickstart works

Prerequisites

To run this sample, you need:

Register and download your quickstart app

You have two options to start your quickstart application: Express (Option 1 below), and Manual (Option 2)

Option 1: Register and auto configure your app and then download your code sample

  1. Go to the Azure portal - App registrations quickstart experience.
  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.

Option 2: Register and manually configure your application and code sample

Step 1: Register your application

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

  1. Sign in to the Azure portal.
  2. If you have access to multiple tenants, use the Directories + subscriptions filter in the top menu to switch to the tenant in which you want to register the application.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations > New registration.
  5. Enter a Name for your application, for example Daemon-console. Users of your app might see this name, and you can change it later.
  6. Select Register.
  7. Under Manage, select Certificates & secrets.
  8. 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.
  9. Under Manage, select API Permissions > Add a permission. Select Microsoft Graph.
  10. Select Application permissions.
  11. Under User node, select User.Read.All, then select Add permissions.

Download and configure the quickstart app

Step 1: Configure your application in Azure portal

For the code sample in this quickstart to work, create a client secret and add Graph API's User.Read.All application permission.

Already configured Your application is configured with these attributes.

Step 2: Download the Python project

Note

Enter_the_Supported_Account_Info_Here

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 Azure portal. To generate a new key, go to Certificates & secrets page.

If 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

If you are a global tenant administrator, go to API Permissions page in App registrations in the Azure portal and select Grant admin consent for {Tenant Name} (Where {Tenant Name} is the name of your directory).

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

Step 4: Run the application

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 Azure AD 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 Azure Portal.
config["client_id"] Is the Application (client) ID for the application registered in the Azure portal. You can find this value in the app's Overview page in the Azure portal.
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 Azure portal (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 Azure Portal.

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.