> Every page of the ganymede website is listed in https://eugo.io/docs/ganymede/llms.txt.

# Microsoft Authentication Library (MSAL) for Python

> Microsoft Authentication Library (MSAL) for Python: Authenticate to Azure in Python. A Python demo notebook from ganymede.

Web page: https://eugo.io/docs/ganymede/demo_notebooks/geospatial/microsoft/azure/msal/
Notebook: https://eugo.io/docs/ganymede/demo_notebooks/geospatial/microsoft/azure/msal/msal.ipynb (source: https://github.com/eugo-inc/ganymede/blob/main/demo_notebooks/geospatial/microsoft/azure/msal.ipynb)

Description:
- Authenticate to Azure in Python

Resources:
- [GitHub] https://github.com/AzureAD/microsoft-authentication-library-for-python
- [Examples] https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample
- [Microsoft Docs] https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app

Source and license:
- Some of these examples are adapted from the MSAL for Python README (https://github.com/AzureAD/microsoft-authentication-library-for-python), Copyright (c) Microsoft Corporation, licensed under MIT. That code stays under its own license; see [THIRD_PARTY_NOTICES.md](https://github.com/eugo-inc/ganymede/blob/main/THIRD_PARTY_NOTICES.md).

## Environment variables

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

## Example 1

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

```python
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
```
