Skip to content

Microsoft Authentication Library (MSAL) for Python

Description:

  • Authenticate to Azure in Python

Resources:

Source and license:

This notebook reads these environment variables. Set them before you start Jupyter:

  • AZURE_CLIENT_ID: the application (client) id of your app registration or service principal.
  • AZURE_TENANT_ID: your Microsoft Entra (Azure AD) tenant id.

The example signs in with the device code flow, so the app registration must allow public client flows (Authentication > Allow public client flows).

Sign in as a user from a public client app: use a cached token if there is one, otherwise run the device code flow

import os
from msal import PublicClientApplication
scopes = ["User.Read"]
app = PublicClientApplication(
os.environ["AZURE_CLIENT_ID"],
authority=f"https://login.microsoftonline.com/{os.environ['AZURE_TENANT_ID']}")
result = None
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(scopes, account=chosen)
if not result:
# So no suitable token exists in cache. Let's get a new one with the device code flow
flow = app.initiate_device_flow(scopes=scopes)
if "user_code" not in flow:
raise RuntimeError(f"Could not start the device code flow: {flow.get('error_description')}")
print(flow["message"]) # tells you which page to open and which code to enter there
result = app.acquire_token_by_device_flow(flow) # waits until you have signed in
if "access_token" in result:
# Never print the token itself: notebook outputs are easy to commit by mistake
print(f"Got an access token for {scopes}; it expires in {result.get('expires_in')} seconds")
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You may need this when reporting a bug

ganymede is made by Eugo