[Python] Azure: Use client ID and secret to authenticate to App on app service (msal)

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to use msal for authenticating to a FastAPI app hosted on Azure app service.

    I have an app registration for the authorization to the app service. I am assuming that the token I get doesn't actually grant access to my API since I get a token but then get a 401 error when using the token.

    Any suggestions on what should be investigated on the setup for this to work?

    import msal
    import requests

    client_id = 'your-client-id'
    client_secret = 'your-client-secret'
    tenant_id = 'your-tenant-id'
    authority = f"https://login.microsoftonline.com/{tenant_id}"
    scope = ["https://management.azure.com/.default"]

    app = msal.ConfidentialClientApplication(
    client_id,
    authority=authority,
    client_credential=client_secret
    )

    result = app.acquire_token_for_client(scopes=scope)

    if "access_token" in result:
    print("Access token acquired:", result["access_token"])
    headers = {
    'Authorization': f'Bearer {access_token}',
    'Content-Type': 'application/json'
    }
    else:
    print("None Found")
    headers={}

    # returns a 401
    response = requests.get
    url="myapi.com/endpoint"
    headers=headers,
    ).json()

    Continue reading...

Compartilhe esta Página