Muokkaa

Jaa


Microsoft Authentication Library (MSAL) for Python

The Microsoft Authentication Library (MSAL) for Python library enables you to sign in users or apps with Microsoft identities (Microsoft Entra ID, Microsoft Accounts, and Azure AD B2C accounts). Using MSAL Python, you can acquire tokens from Microsoft Entra ID to call protected web APIs such as Microsoft Graph, other Microsoft APIs, or your own APIs.

Prerequisites

Install the package

Install the MSAL for Python package. You can find MSAL Python on PyPI.

pip install msal

Identity concepts

MSAL Python is part of the Microsoft identity platform ecosystem. It's important to familiarize yourself with the following concepts to effectively use MSAL Python to protect your applications and APIs:

Usage scenarios

To use MSAL Python, register an application with the Microsoft identity platform. You'll need an Azure account with an active subscription. Create a free account if you don't have one. You can register your app in a customer tenant or workforce tenant.

Applications can use MSAL Python to acquire tokens for accessing protected APIs. Different app types acquire tokens using different auth flows. The supported app types include desktop applications, web applications, web APIs, and applications running on devices that don't have a browser (such as IoT devices).

In MSAL Python, applications are categorized as follows:

For more information, see the documentation on public client and confidential client apps and the different app types and their auth flows in the Microsoft identity platform.

After determining whether your application is a public or confidential client application, you can use MSAL Python to acquire tokens for different scenarios.

Basic usage

Acquiring tokens with MSAL Python follows a three-step pattern. There will be some variations for different flows. If you would like to see them in action, download our samples.

  1. MSAL relies on a clean separation between public client and confidential client applications. Therefore, create either a PublicClientApplication or a ConfidentialClientApplication instance and reuse it during the lifecycle of your application. For example, for a public client application, the initialization code might look like this:

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

    The authority value varies depending on the type of accounts you are signing-in and the kind of tenant your app is registered in. For example, to sign-in both work and personal Microsoft accounts provisioned in workforce tenants (Microsoft Entra ID) you would use https://login.microsoftonline.com/common. For customer accounts provisioned in customer tenants, your authority will take a form like https://<subdomain>.ciamlogin.com. For more information, see token issuer documentation.

  2. Try and obtain the tokens from the cache first. The API model in MSAL provides you explicit control on how to utilize the token cache. While the caching part is technically optional, we highly recommend you to use it in your application. Using the cache you can ensure that you're not making any extra API calls and handle the token refresh automatically.

    # initialize result variable to hole the token response
    result = None 
    
    # 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(["User.Read"], account=chosen)
    
  3. If there's no suitable token in the cache or you chose to skip the previous step, send a request to Microsoft Entra ID to get a token. There are different methods based on your client type and scenario, but for the purposes of the example we're showing how to use acquire_token_interactive, which prompts the user to provide their credentials.

    if not result:
        # So no suitable token exists in cache. Let's get a new one from Azure AD.
        result = app.acquire_token_interactive(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
    
  4. Save the code into a Python file locally, such as msaltest.py.

  5. Run the code by executing python .\msalpytest.py. The following visual shows the sign-in experience for this example.

    Example of an app prompting the user to sign in with their account

  6. Once the authentication is completed and you closed the browser, you should be able to see the access token printed in the terminal.

Samples

There are several samples you can use to get started with MSAL Python.

  • Samples from the library repository. These samples demonstrate the different configurations and auth flows that you implement using MSAL Python.
  • A single repository with samples used in our documentation. These samples have supporting documentation to help you build and replicate them from scratch.

References

  • MSAL Python library repository on GitHub
  • MSAL Python releases on GitHub.

See also