Skip to content

corteva/msal-requests-auth

Repository files navigation

msal-requests-auth

Authentication using python requests and MSAL. This uses the MSAL cache for repeated requests.

All Contributors

image

image

image

image

image

image

image

image

Bugs/Questions

Usage

Compatible with:

Device Code Flow

Note

By default, DeviceCodeAuth copys the code to your clipboard and opens a webbrowser. To disable, either set headless=True when initializing DeviceCodeAuth or set the environment variable MSAL_REQUESTS_AUTH_HEADLESS to true.

  • New in version 0.2.0: headless
  • New in version 0.6.0: MSAL_REQUESTS_AUTH_HEADLESS environment variable
  • New in version 0.7.0: KeyringTokenCache
import requests
import msal
from msal_requests_auth.auth import DeviceCodeAuth
from msal_requests_auth.cache import KeyringTokenCache

client_id = "<client ID from Azure AD>"
tenant_id = "<tenant ID from Azure AD>"
application_id = "<client ID of application you want to get a token for from Azure AD>"

with KeyringTokenCache() as token_cache:
    app = msal.PublicClientApplication(
        client_id,
        authority=f"https://login.microsoftonline.com/{tenant_id}/",
        token_cache=token_cache,
    )
    auth = DeviceCodeAuth(
        client=app,
        scopes=[f"{application_id}/.default"],
    )
    response = requests.get(
        endpoint,
        auth=auth,
    )

Client Credentials Flow

import requests
import msal
from msal_requests_auth.auth import ClientCredentialAuth

client_id = "<client ID from Azure AD>"
client_secret = "<client secret for client in Azure AD>"
tenant_id = "<tenant ID from Azure AD>"
application_id = "<client ID of application you want to get a token for from Azure AD>"
app = msal.ConfidentialClientApplication(
    client_id,
    authority=(f"https://login.microsoftonline.com/{tenant_id}/"),
    client_credential=client_secret,
)
auth = ClientCredentialAuth(
    client=app,
    scopes=[f"{application_id}/.default"],
)
response = requests.get(
    endpoint,
    auth=auth,
)

Installation

To install msal-requests-auth, run this command in your terminal:

$ python -m pip install msal_requests_auth

If you use conda:

$ conda install -c conda-forge msal_requests_auth

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.