### File-Based Token Cache Persistence Source: https://msal-python.readthedocs.io/en/latest This example demonstrates how to implement file-based, unencrypted token cache persistence using SerializableTokenCache. It includes logic to load the cache from a file on startup and save it on exit, with an option to persist only when the cache state has changed. ```python import os, atexit, msal cache_filename = os.path.join( # Persist cache into this file os.getenv( # Automatically wipe out the cache from Linux when user's ssh session ends. # See also https://github.com/AzureAD/microsoft-authentication-library-for-python/issues/690 "XDG_RUNTIME_DIR", ""), "my_cache.bin") cache = msal.SerializableTokenCache() if os.path.exists(cache_filename): cache.deserialize(open(cache_filename, "r").read()) atexit.register(lambda: open(cache_filename, "w").write(cache.serialize()) # Hint: The following optional line persists only when state changed if cache.has_state_changed else None ) app = msal.ClientApplication(..., token_cache=cache) ... ``` -------------------------------- ### Configure HTTP Cache for Persistence Source: https://msal-python.readthedocs.io/en/latest Example of persisting the HTTP cache across different CLI runs by using a file-based dictionary. This allows for improved performance in command-line applications by reusing cached HTTP responses. ```python import os import json class FileCache(dict): def __init__(self, filename): self.filename = filename if os.path.exists(filename): with open(filename, "r") as f: super().__init__(json.load(f)) else: super().__init__() def __setitem__(self, key, value): super().__setitem__(key, value) with open(self.filename, "w") as f: json.dump(self, f) app = PublicClientApplication( client_id, http_cache=FileCache("my_http_cache.json") ) ``` -------------------------------- ### SerializableTokenCache Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt An example subclass of TokenCache demonstrating token serialization. ```APIDOC ## SerializableTokenCache ### Description An example subclass of TokenCache demonstrating token serialization. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Dynamic Client Assertion with Callable Source: https://msal-python.readthedocs.io/en/latest For long-running confidential clients, use a callable that MSAL can invoke on demand to obtain a fresh assertion. This example shows reading a token from a file. ```python def get_client_assertion(): # e.g. read the projected service-account token from disk with open("/var/run/secrets/azure/tokens/azure-identity-token") as f: return f.read() app = ConfidentialClientApplication( "client_id", client_credential={"client_assertion": get_client_assertion}, ... ) ``` -------------------------------- ### acquire_token_by_username_password Source: https://msal-python.readthedocs.io/en/latest Gets a token for a given resource via user credentials. This method is subject to constraints for Username Password Flow. ```APIDOC ## acquire_token_by_username_password ### Description Gets a token for a given resource via user credentials. See this page for constraints of Username Password Flow. https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **username** (str) - Typically a UPN in the form of an email address. * **password** (str) - The password. * **scopes** (list[str]) - Scopes requested to access a protected API (a resource). * **claims_challenge** - The claims_challenge parameter requests specific claims requested by the resource provider in the form of a claims_challenge directive in the www-authenticate header to be returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token. It is a string of a JSON object which contains lists of claims being requested from these locations. * **auth_scheme** (object) - You can provide an `msal.auth_scheme.PopAuthScheme` object so that MSAL will get a Proof-of-Possession (POP) token for you. New in version 1.26.0. ### Request Example None ### Response #### Success Response A dict representing the json response from Microsoft Entra: A successful response would contain “access_token” key. #### Error Response A dict representing the json response from Microsoft Entra: an error response would contain “error” and usually “error_description”. #### Response Example None ### Deprecation Note [Deprecated] This API is deprecated for public client flows and will be removed in a future release. Use a more secure flow instead. Migration guide: https://aka.ms/msal-ropc-migration ``` -------------------------------- ### acquire_token_by_auth_code_flow Source: https://msal-python.readthedocs.io/en/latest Initiates the authorization code flow by generating an authentication URI and associated state. The caller is responsible for guiding the user to the URI and then processing the subsequent response. ```APIDOC ## acquire_token_by_auth_code_flow ### Description Initiates the authorization code flow by generating an authentication URI and associated state. The caller is responsible for guiding the user to the URI and then processing the subsequent response. ### Parameters #### Query Parameters - **prompt** (str) - By default, no prompt value will be sent, not even string "none". You will have to specify a value explicitly. Its valid values are the constants defined in `Prompt`. - **login_hint** (str) - Optional. Identifier of the user. Generally a User Principal Name (UPN). - **domain_hint** (str) - Can be one of “consumers” or “organizations” or your tenant domain “contoso.com”. If included, it will skip the email-based discovery process that user goes through on the sign-in page, leading to a slightly more streamlined user experience. - **max_age** (int) - OPTIONAL. Maximum Authentication Age. Specifies the allowable elapsed time in seconds since the last time the End-User was actively authenticated. If the elapsed time is greater than this value, Microsoft identity platform will actively re-authenticate the End-User. MSAL Python will also automatically validate the auth_time in ID token. New in version 1.15. - **response_mode** (str) - OPTIONAL. Specifies the method with which response parameters should be returned. The default value is equivalent to `query`. For even better security, we recommend using the value `form_post`. In “form_post” mode, response parameters will be encoded as HTML form values that are transmitted via the HTTP POST method and encoded in the body using the application/x-www-form-urlencoded format. Valid values can be either “form_post” or “query” (the default). ### Returns - **auth_uri** (str) - Guide user to visit this URI. - **state** (str) - You may choose to verify it by yourself, or just let acquire_token_by_auth_code_flow() do that for you. - **...** (any) - Everything else are reserved and internal. ### Usage 1. Store the returned dictionary (typically inside the current session). 2. Guide the end user to visit the `auth_uri`. 3. Relay this dictionary and subsequent auth response to `acquire_token_by_auth_code_flow()`. ``` -------------------------------- ### PublicClientApplication Initialization Source: https://msal-python.readthedocs.io/en/latest Demonstrates how to initialize a PublicClientApplication with various configuration options, including HTTP cache and instance discovery settings. ```APIDOC ## PublicClientApplication Initialization ### Description Initializes a PublicClientApplication with client ID, authority, and optional configurations like HTTP cache, instance discovery, PII logging, and OIDC authority. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **client_id** (string) - Required - The application's client ID. * **authority** (string) - Optional - The authority URL for authentication. * **http_cache** (object) - Optional - An object for persisting HTTP cache. * **instance_discovery** (boolean) - Optional - Controls whether to perform instance discovery. Defaults to True. * **enable_pii_log** (boolean) - Optional - Enables logging of PII. Defaults to False. * **oidc_authority** (string) - Optional - An OIDC authority URL. ### Request Example ```python import msal app = msal.PublicClientApplication( "your_client_id", authority="https://login.microsoftonline.com/common", instance_discovery=True, # or False enable_pii_log=True, # or False oidc_authority="https://contoso.com/tenant" ) ``` ### Response #### Success Response (200) * **PublicClientApplication object** - An initialized MSAL PublicClientApplication instance. ``` -------------------------------- ### Initialize PublicClientApplication Source: https://msal-python.readthedocs.io/en/latest Instantiate a PublicClientApplication with a client ID and authority. The authority can be a string representing the Microsoft Entra ID endpoint. ```python from msal import PublicClientApplication app = PublicClientApplication("my_client_id", authority=my_authority, ...) ``` -------------------------------- ### Initialize PublicClientApplication with HttpCache Source: https://msal-python.readthedocs.io/en/latest Demonstrates initializing a PublicClientApplication with a persisted HTTP cache. This cache is useful for storing HTTP responses and does not contain sensitive information. ```python app = msal.PublicClientApplication( "your_client_id", ..., http_cache=persisted_http_cache, # Utilize persisted_http_cache ..., #token_cache=..., # You may combine the old token_cache trick # Please refer to token_cache recipe at # https://msal-python.readthedocs.io/en/latest/#msal.SerializableTokenCache ) app.acquire_token_interactive(["your", "scope"], ...) ``` -------------------------------- ### Configure Client Certificate from PFX File Source: https://msal-python.readthedocs.io/en/latest Use a dictionary to specify the path to a PFX file for client authentication. The 'public_certificate' option is needed for Subject Name/Issuer Auth. ```python { "private_key_pfx_path": "/path/to/your.pfx", # Added in version 1.29.0 "public_certificate": True, # Only needed if you use Subject Name/Issuer auth. Added in version 1.30.0 "passphrase": "Passphrase if the private_key is encrypted (Optional)", } ``` -------------------------------- ### PublicClientApplication Constructor Source: https://msal-python.readthedocs.io/en/latest Initializes a new instance of the PublicClientApplication class. This constructor is similar to ClientApplication.__init__ but requires client_credential to be None. It supports various broker enablement options for different operating systems. ```APIDOC ## PublicClientApplication Constructor ### Description Initializes a new instance of the PublicClientApplication class. This constructor is similar to ClientApplication.__init__ but requires client_credential to be None. It supports various broker enablement options for different operating systems. ### Parameters #### Parameters * **_client_id_** (string) - The client ID of the application. * **_client_credential** (string, optional) - This parameter must be None for PublicClientApplication. * **enable_broker_on_windows** (boolean, optional) - Enables broker support on Windows 10+. Defaults to None (broker not used). * **enable_broker_on_mac** (boolean, optional) - Enables broker support on Mac. Defaults to None (broker not used). * **enable_broker_on_linux** (boolean, optional) - Enables broker support on Linux (including WSL). Defaults to None (broker not used). * **enable_broker_on_wsl** (boolean, optional) - Enables broker support on WSL. Defaults to None (broker not used). ### Broker Configuration Notes - A broker enhances security by acting as a device identity factor and enables Single Sign-On (SSO). - To opt-in to broker usage, set the relevant `enable_broker_on_...` parameters to `true` and install the `msal[broker]` dependency. - MSAL Python has fallback behaviors for broker initialization failures, either erroring out or silently falling back to non-broker flows. ``` -------------------------------- ### Generate PFX File from Key and PEM Source: https://msal-python.readthedocs.io/en/latest Command to generate a .pfx file from a private key (.key) and a certificate (.pem) file using OpenSSL. ```bash openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.pem ``` -------------------------------- ### ClientApplication Constructor Source: https://msal-python.readthedocs.io/en/latest Initializes a ClientApplication instance. This is a base class and is typically subclassed by PublicClientApplication or ConfidentialClientApplication. ```APIDOC ## ClientApplication Constructor ### Description Initializes a ClientApplication instance. This is a base class and is typically subclassed by PublicClientApplication or ConfidentialClientApplication. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **client_id** (str) – Your app has a client_id after you register it on Microsoft Entra admin center. * **client_credential** (Union[dict, str, None]) – For `PublicClientApplication`, you use None here. For `ConfidentialClientApplication`, it supports many different input formats for different scenarios. Support using a client secret. Just feed in a string, such as `"your client secret"`. Support using a certificate in X.509 (.pem) format. Deprecated because it uses SHA-1 thumbprint, unless you are still using ADFS which supports SHA-1 thumbprint only. Please use the .pfx option documented later in this page. Feed in a dict in this form: ``` { "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format", "thumbprint": "An SHA-1 thumbprint such as A1B2C3D4E5F6..." "Changed in version 1.35.0, if thumbprint is absent" "and a public_certificate is present, MSAL will" "automatically calculate an SHA-256 thumbprint instead.", "passphrase": "Needed if the private_key is encrypted (Added in version 1.6.0)", "public_certificate": "...-----BEGIN CERTIFICATE-----...", # Needed if you use Subject Name/Issuer auth. Added in version 0.5.0. } ``` MSAL Python requires a “private_key” in PEM format. If your cert is in PKCS12 (.pfx) format, you can convert it to X.509 (.pem) format, by `openssl pkcs12 -in file.pfx -out file.pem -nodes`. The thumbprint is available in your app’s registration in Azure Portal. Alternatively, you can calculate the thumbprint. `public_certificate` (optional) is public key certificate which will be sent through ‘x5c’ JWT header. This is useful when you use Subject Name/Issuer Authentication which is an approach to allow easier certificate rotation. Per specs, “the certificate containing the public key corresponding to the key used to digitally sign the JWS MUST be the first certificate. This MAY be followed by additional certificates, with each subsequent certificate being the one used to certify the previous one.” However, your certificate’s issuer may use a different order. So, if your attempt ends up with an error AADSTS700027 - “The provided signature value did not match the expected signature value”, you may try use only the leaf cert (in PEM/str format) instead. Supporting raw assertion obtained from elsewhere _Added in version 1.13.0_ : It can also be a completely pre-signed assertion that you’ve assembled yourself. Simply pass a container containing only the key “client_assertion”, like this: ``` { "client_assertion": "...a JWT with claims aud, exp, iss, jti, nbf, and sub..." } ``` Note A pre-signed JWT string has a fixed expiration. Long-running confidential client applications (for example, workloads using AKS workload identity federation, or any other dynamic credential source) should instead pass a **callable** which MSAL will invoke on demand to obtain a fresh assertion: ```python def get_client_assertion(): # e.g. read the projected service-account token from disk with open("/var/run/secrets/azure/tokens/azure-identity-token") as f: return f.read() app = ConfidentialClientApplication( "client_id", client_credential={"client_assertion": get_client_assertion}, ..., ) ``` The callable is only invoked when MSAL needs to send a token request on the wire (the in-memory token cache transparently avoids unnecessary calls). If your callback is itself expensive (for example it calls out to a key vault), wrap it in `msal.AutoRefresher` to memoize the assertion for its lifetime: ```python from msal import AutoRefresher smart_callback = AutoRefresher(get_client_assertion, expires_in=3600) app = ConfidentialClientApplication( "client_id", client_credential={"client_assertion": smart_callback}, ..., ) ``` * **authority** (None) – * **validate_authority** (bool) – * **token_cache** (None) – * **http_client** (None) – * **verify** (bool) – * **proxies** (None) – * **timeout** (None) – * **client_claims** (None) – * **app_name** (None) – * **app_version** (None) – * **client_capabilities** (None) – * **azure_region** (None) – * **exclude_scopes** (None) – * **http_cache** (None) – * **instance_discovery** (None) – * **allow_broker** (None) – * **enable_pii_log** (None) – * **oidc_authority** (None) – ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Managed Identity Client Initialization with Requests Session and Retries Source: https://msal-python.readthedocs.io/en/latest Demonstrates creating a ManagedIdentityClient with a requests.Session object configured with exponential backoff retries. This is useful for handling transient network issues. ```python import msal, requests from requests.adapters import HTTPAdapter, Retry s = requests.Session() retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[ 429, 500, 501, 502, 503, 504]) s.mount('https://', HTTPAdapter(max_retries=retries)) managed_identity = ... client = msal.ManagedIdentityClient(managed_identity, http_client=s) ``` -------------------------------- ### initiate_device_flow Source: https://msal-python.readthedocs.io/en/latest Initiates a Device Flow instance, which is used later in acquire_token_by_device_flow(). This method is suitable for devices that cannot easily open a browser. ```APIDOC ## initiate_device_flow ### Description Initiate a Device Flow instance, which will be used in `acquire_token_by_device_flow()`. ### Method initiate_device_flow ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **scopes** (list [str]) - Scopes requested to access a protected API (a resource). - **claims_challenge** (str) - The claims_challenge parameter requests specific claims requested by the resource provider in the form of a claims_challenge directive in the www-authenticate header to be returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token. It is a string of a JSON object which contains lists of claims being requested from these locations. ### Returns None explicitly documented, but implies a device flow instance is returned for subsequent use. ``` -------------------------------- ### ClientApplication Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt The base class for client applications in MSAL Python, providing core authentication functionalities. ```APIDOC ## ClientApplication ### Description The base class for client applications in MSAL Python, providing core authentication functionalities. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Dynamic Managed Identity Configuration from Environment Variable Source: https://msal-python.readthedocs.io/en/latest Loads Managed Identity configuration dynamically from an environment variable, allowing for different configurations across deployments. Asserts that the environment variable is set. ```python import json, os, msal, requests config = os.getenv("MY_MANAGED_IDENTITY_CONFIG") assert config, "An ENV VAR with value should exist" client = msal.ManagedIdentityClient( json.loads(config), http_client=requests.Session(), ) token = client.acquire_token_for_client("resource") ``` -------------------------------- ### MSAL Python Scenarios Overview Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt This section outlines different application scenarios supported by MSAL Python, with visual aids and links to relevant samples. ```APIDOC ## MSAL Python Scenarios ### Description This section provides a visual map to help you locate your application scenario and find corresponding MSAL Python samples. It covers scenarios for acquiring tokens for signed-in users and for daemon applications acquiring tokens for themselves. ### Scenarios Covered * **Web Apps:** Acquire tokens for signed-in users. * Link to Microsoft Learn quickstart: [https://learn.microsoft.com/azure/active-directory/develop/web-app-quickstart?pivots=devlang-python](https://learn.microsoft.com/azure/active-directory/develop/web-app-quickstart?pivots=devlang-python) * **Desktop Apps:** Acquire tokens for signed-in users (interactive flow). * Link to sample: [https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/sample/interactive_sample.py](https://github.com/AzureAD/microsoft-authentication-library-for-python/blob/dev/sample/interactive_sample.py) * **Browserless Apps:** Acquire tokens using device code flow. * Link to sample: [https://github.com/Azure-Samples/ms-identity-python-devicecodeflow](https://github.com/Azure-Samples/ms-identity-python-devicecodeflow) * **Daemon Apps:** Acquire tokens representing the application itself (not a user). * Link to sample: [https://github.com/Azure-Samples/ms-identity-python-daemon](https://github.com/Azure-Samples/ms-identity-python-daemon) ### Additional Samples * ADAL-to-MSAL migration samples are available in the project codebase: [https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample](https://github.com/AzureAD/microsoft-authentication-library-for-python/tree/dev/sample) ``` -------------------------------- ### Handle Authentication Response in Web App Source: https://msal-python.readthedocs.io/en/latest Illustrates how to handle the authentication response within a web application controller. This snippet shows token acquisition and error handling for the authorization code flow. ```python def authorize(): # A controller in a web app try: result = msal_app.acquire_token_by_auth_code_flow( session.get("flow", {}), request.args) if "error" in result: return render_template("error.html", result) use(result) # Token(s) are available in result and cache except ValueError: # Usually caused by CSRF pass # Simply ignore them return redirect(url_for("index")) ``` -------------------------------- ### initiate_auth_code_flow Source: https://msal-python.readthedocs.io/en/latest Initiates an authorization code flow, preparing for subsequent token acquisition. ```APIDOC ## initiate_auth_code_flow ### Description Initiates an authorization code flow. After the response is received at the redirect URI, `acquire_token_by_auth_code_flow()` can be used to complete the authentication and authorization process. ### Parameters * **scopes** (list) - Required. A list of case-sensitive strings representing the requested scopes. * **redirect_uri** (str) - Optional. If not specified, the server will use the pre-registered redirect URI. * **state** (str) - Optional. An opaque value used by the client to maintain state between the request and callback. If absent, the library will generate one internally. * **prompt** (str) - Optional. Specifies the prompt behavior for the user's login. * **login_hint** (str) - Optional. Identifier of the user, generally a User Principal Name (UPN). * **domain_hint** (str) - Optional. Can be "consumers", "organizations", or a specific tenant domain. * **claims_challenge** (str) - Optional. A JSON string representing claims requested by the resource provider. * **max_age** (int) - Optional. Specifies the maximum acceptable age of the authentication. * **response_mode** (str) - Optional. Specifies how the response should be encoded. ``` -------------------------------- ### is_pop_supported Source: https://msal-python.readthedocs.io/en/latest Checks if the current client supports Proof-of-Possession Access Tokens. ```APIDOC ## is_pop_supported ### Description Returns True if this client supports Proof-of-Possession Access Token. ### Method GET (implied) ### Endpoint N/A (Method call) ### Returns - **boolean** - True if PoP is supported, False otherwise. ``` -------------------------------- ### Prompt Class Source: https://msal-python.readthedocs.io/en/latest The Prompt class defines constant strings for the 'prompt' parameter used in authentication requests, adhering to OpenID Connect Core specifications. ```APIDOC ## Prompt Class ### Description This class defines the constant strings for prompt parameter. The values are based on https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest ### Constants - **SELECT_ACCOUNT**: 'select_account' - **NONE**: 'none' - **CONSENT**: 'consent' - **LOGIN**: 'login' ``` -------------------------------- ### Prompt Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Defines the prompt behavior for interactive authentication requests. ```APIDOC ## Prompt ### Description Defines the prompt behavior for interactive authentication requests. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Attributes - **SELECT_ACCOUNT** (str) - Select an account. - **NONE** (str) - No prompt. - **CONSENT** (str) - Prompt for consent. - **LOGIN** (str) - Prompt for login. ``` -------------------------------- ### Persist HTTP Cache in CLI Script Source: https://msal-python.readthedocs.io/en/latest Add these lines at the beginning of your CLI script to manage an HTTP cache using pickle. This allows the cache to be saved to a file and reloaded on subsequent runs. ```python import sys, atexit, pickle, logging http_cache_filename = sys.argv[0] + ".http_cache" try: with open(http_cache_filename, "rb") as f: persisted_http_cache = pickle.load(f) # Take a snapshot except ( FileNotFoundError, # Or IOError in Python 2 pickle.UnpicklingError, # A corrupted http cache file AttributeError, # Cache created by a different version of MSAL ): persisted_http_cache = {} # Recover by starting afresh except: logging.exception("You may want to debug this") persisted_http_cache = {} # Recover by starting afresh atexit.register(lambda: pickle.dump( # When exit, flush it back to the file. # It may occasionally overwrite another process's concurrent write, # but that is fine. Subsequent runs will reach eventual consistency. persisted_http_cache, open(http_cache_file, "wb"))) ``` -------------------------------- ### MSAL Python API Reference - ClientApplication Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Details on the ClientApplication class, which serves as the base for public and confidential client applications in MSAL Python. ```APIDOC ## ClientApplication ### Description The `ClientApplication` class is a fundamental component in MSAL Python, providing a base for both public and confidential client applications. It handles the core logic for acquiring and managing tokens, supporting various authentication flows. ### Public API The public API is defined within the `msal/__init__.py` source file. Only documented methods are guaranteed to be backward-compatible until the next major version. Internal helpers may change without notice. ### Key Concepts * **Public Client Applications:** Applications that run on a user's device (e.g., desktop, mobile) and cannot securely store a client secret. They typically use flows like Authorization Code Flow with PKCE or Device Code Flow. * **Confidential Client Applications:** Applications that run on a server and can securely store a client secret (e.g., web apps, daemon apps). They can use flows like Authorization Code Flow or Client Credentials Flow. ### Usage MSAL Python separates these two types of applications into distinct classes with specific methods tailored to their respective authentication scenarios. Refer to the specific client application classes for detailed method documentation. ``` -------------------------------- ### acquire_token_interactive Source: https://msal-python.readthedocs.io/en/latest Acquires a token interactively by opening a local browser for user authentication. It supports various parameters to customize the authentication flow, including scopes, prompts, login hints, and claims challenges. ```APIDOC ## acquire_token_interactive ### Description Acquire token interactively i.e. via a local browser. Prerequisite: In Azure Portal, configure the Redirect URI of your “Mobile and Desktop application” as `http://localhost`. If you opts in to use broker during `PublicClientApplication` creation, your app also need this Redirect URI: `ms-appx-web://Microsoft.AAD.BrokerPlugin/YOUR_CLIENT_ID` ### Method acquire_token_interactive ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **scopes** (list) - It is a list of case-sensitive strings. - **prompt** (str) - By default, no prompt value will be sent, not even string "none". You will have to specify a value explicitly. Its valid values are the constants defined in `Prompt`. - **login_hint** (str) - Optional. Identifier of the user. Generally a User Principal Name (UPN). - **domain_hint** (str) - Can be one of “consumers” or “organizations” or your tenant domain “contoso.com”. If included, it will skip the email-based discovery process that user goes through on the sign-in page, leading to a slightly more streamlined user experience. More information on possible values available in Auth Code Flow doc and domain_hint doc. - **claims_challenge** (str) - The claims_challenge parameter requests specific claims requested by the resource provider in the form of a claims_challenge directive in the www-authenticate header to be returned from the UserInfo Endpoint and/or in the ID Token and/or Access Token. It is a string of a JSON object which contains lists of claims being requested from these locations. - **timeout** (int) - This method will block the current thread. This parameter specifies the timeout value in seconds. Default value `None` means wait indefinitely. - **port** (int) - The port to be used to listen to an incoming auth response. By default we will use a system-allocated port. (The rest of the redirect_uri is hard coded as `http://localhost`.) - **extra_scopes_to_consent** (list) - “Extra scopes to consent” is a concept only available in Microsoft Entra. It refers to other resources you might want to prompt to consent for, in the same interaction, but for which you won’t get back a token for in this particular operation. - **max_age** (int) - OPTIONAL. Maximum Authentication Age. Specifies the allowable elapsed time in seconds since the last time the End-User was actively authenticated. If the elapsed time is greater than this value, Microsoft identity platform will actively re-authenticate the End-User. MSAL Python will also automatically validate the auth_time in ID token. New in version 1.15. - **parent_window_handle** (int) - OPTIONAL. If your app does not opt in to use broker, you do not need to provide a `parent_window_handle` here. If your app opts in to use broker, `parent_window_handle` is required. If your app is a GUI app running on Windows or Mac system, you are required to also provide its window handle, so that the sign-in window will pop up on top of your window. If your app is a console app running on Windows or Mac system, you can use a placeholder `PublicClientApplication.CONSOLE_WINDOW_HANDLE`. Most Python scripts are console apps. New in version 1.20.0. - **on_before_launching_ui** (function) - A callback with the form of `lambda ui="xyz", **kwargs: print("A {}".format(ui))", where `ui` will be either “browser” or “broker”. You can use it to inform your end user to expect a pop-up window. New in version 1.20.0. - **auth_scheme** (object) - You can provide an `msal.auth_scheme.PopAuthScheme` object so that MSAL will get a Proof-of-Possession (POP) token for you. New in version 1.26.0. ### Returns - A dict containing no “error” key, and typically contains an “access_token” key. - A dict containing an “error” key, when token refresh failed. ``` -------------------------------- ### Client Credential Dictionary for Certificate Authentication Source: https://msal-python.readthedocs.io/en/latest Use this dictionary format when providing a client certificate for authentication. It supports private keys in PEM format, a thumbprint, and an optional passphrase for encrypted keys. The public certificate can also be included for Subject Name/Issuer authentication. ```python { "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format", "thumbprint": "An SHA-1 thumbprint such as A1B2C3D4E5F6...", "passphrase": "Needed if the private_key is encrypted (Added in version 1.6.0)", "public_certificate": "...-----BEGIN CERTIFICATE-----...", } ``` -------------------------------- ### acquire_token_interactive Source: https://msal-python.readthedocs.io/en/latest Acquires a token interactively by prompting the user for credentials. This method is suitable for client applications where a user can be present. ```APIDOC ## acquire_token_interactive ### Description Acquires an interactive token by prompting the user for authentication. This method is typically used in applications where user interaction is possible. ### Method `acquire_token_interactive(scopes, **kwargs)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **scopes** (list[str]) - Required - A list of scopes requested for the token. * **kwargs** - Additional keyword arguments for interactive token acquisition. ### Request Example ```python result = app.acquire_token_interactive(["your", "scope"]) ``` ### Response #### Success Response (200) * **dict** - A dictionary containing the acquired token and other related information, or an error object if acquisition fails. ``` -------------------------------- ### System Assigned Managed Identity Configuration (Dict) Source: https://msal-python.readthedocs.io/en/latest Represents a system-assigned managed identity as a Python dictionary. ```python {"ManagedIdentityIdType": "SystemAssigned", "Id": None} ``` -------------------------------- ### PopAuthScheme Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Supports Proof of Possession (PoP) tokens, used as the `auth_scheme` parameter. ```APIDOC ## PopAuthScheme ### Description Supports Proof of Possession (PoP) tokens, used as the `auth_scheme` parameter. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Attributes - **HTTP_GET** (str) - HTTP GET method. - **HTTP_POST** (str) - HTTP POST method. - **HTTP_PUT** (str) - HTTP PUT method. - **HTTP_DELETE** (str) - HTTP DELETE method. - **HTTP_PATCH** (str) - HTTP PATCH method. ``` -------------------------------- ### Build Authority URL with AuthorityBuilder Source: https://msal-python.readthedocs.io/en/latest Construct a custom authority URL using AuthorityBuilder with predefined constants like AZURE_PUBLIC and a tenant name. ```python from msal.authority import ( AuthorityBuilder, AZURE_US_GOVERNMENT, AZURE_CHINA, AZURE_PUBLIC) my_authority = AuthorityBuilder(AZURE_PUBLIC, "contoso.onmicrosoft.com") ``` -------------------------------- ### Managed Identity Support Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt MSAL Python supports Managed Identities for Azure resources. ```APIDOC ## Managed Identity Support ### Description MSAL Python supports Managed Identities for Azure resources. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### PublicClientApplication Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Represents a public client application, such as a desktop or mobile app, that cannot securely store secrets. ```APIDOC ## PublicClientApplication ### Description Represents a public client application, such as a desktop or mobile app, that cannot securely store secrets. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Attributes - **CONSOLE_WINDOW_HANDLE** (str) - Handle for the console window. ``` -------------------------------- ### Define Client Claims for Token Request Source: https://msal-python.readthedocs.io/en/latest A dictionary of extra claims to be signed by the client's private key. This can override default claims like audience, issuer, and expiration. ```python { "aud": the_token_endpoint, "iss": self.client_id, "sub": same_as_issuer, "exp": now + 10_min, "iat": now, "jti": a_random_uuid } ``` -------------------------------- ### Auth Code Flow Return Structure Source: https://msal-python.readthedocs.io/en/latest This dictionary represents the structure returned by the auth code flow. It contains the authorization URI for the user to visit and a state parameter for verification. The caller is expected to store this information and use it in subsequent steps. ```json { "auth_uri": "https://...", // Guide user to visit this "state": "...", // You may choose to verify it by yourself, // or just let acquire_token_by_auth_code_flow() // do that for you. "...": "...", // Everything else are reserved and internal } ``` -------------------------------- ### Conditionally Disable Instance Discovery Source: https://msal-python.readthedocs.io/en/latest Shows how to conditionally disable Instance Discovery for known authorities. This is recommended when you want MSAL to operate with specific, trusted authorities without performing discovery. ```python known_authorities = frozenset([ "https://contoso.com/adfs", "https://login.azs/foo"]) ... authority = "https://contoso.com/adfs" # Assuming your app will use this app1 = PublicClientApplication( "client_id", authority=authority, # Conditionally disable Instance Discovery for known authorities instance_discovery=authority not in known_authorities, ) ``` -------------------------------- ### SystemAssignedManagedIdentity Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Configuration object for system-assigned managed identity. ```APIDOC ## SystemAssignedManagedIdentity ### Description Configuration object for system-assigned managed identity. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### System Assigned Managed Identity Configuration (JSON) Source: https://msal-python.readthedocs.io/en/latest Represents a system-assigned managed identity as a JSON blob. ```json {"ManagedIdentityIdType": "SystemAssigned", "Id": null} ``` -------------------------------- ### Client Credential Dictionary for Pre-signed Assertion Source: https://msal-python.readthedocs.io/en/latest This format is used when providing a pre-signed JWT assertion. The dictionary should contain a single key, 'client_assertion', with the JWT string as its value. ```python { "client_assertion": "...a JWT with claims aud, exp, iss, jti, nbf, and sub..." } ``` -------------------------------- ### Memoized Client Assertion with AutoRefresher Source: https://msal-python.readthedocs.io/en/latest Wrap an expensive assertion callback with msal.AutoRefresher to memoize the assertion for its lifetime. This prevents repeated calls to the callback if it's costly. ```python from msal import AutoRefresher smart_callback = AutoRefresher(get_client_assertion, expires_in=3600) app = ConfidentialClientApplication( "client_id", client_credential={"client_assertion": smart_callback}, ... ) ``` -------------------------------- ### acquire_token_on_behalf_of Source: https://msal-python.readthedocs.io/en/latest Acquires token using on-behalf-of (OBO) flow. The current app is a middle-tier service which was called with a token representing an end user. The current app can use such token (a user assertion) to request another token to access downstream web API, on behalf of that user. ```APIDOC ## acquire_token_on_behalf_of ### Description Acquires token using on-behalf-of (OBO) flow. The current app is a middle-tier service which was called with a token representing an end user. The current app can use such token (a.k.a. a user assertion) to request another token to access downstream web API, on behalf of that user. The current middle-tier app has no user interaction to obtain consent. ### Method POST (implied) ### Endpoint (Not specified, typically part of the client application's token endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **user_assertion** (str) - Required. The incoming token already received by this app. - **scopes** (list[str]) - Required. Scopes required by downstream API (a resource). - **claims_challenge** (str) - Optional. The claims_challenge parameter requests specific claims requested by the resource provider. ### Request Example ```json { "user_assertion": "", "scopes": ["api://resource/.default"] } ``` ### Response #### Success Response (200) - **access_token** (str) - The acquired access token. #### Response Example ```json { "access_token": "" } ``` #### Error Response - **error** (str) - An error code. - **error_description** (str) - A description of the error. ``` -------------------------------- ### get_accounts Source: https://msal-python.readthedocs.io/en/latest Retrieves a list of accounts that have previously signed in and are present in the cache. ```APIDOC ## get_accounts ### Description Retrieves a list of accounts that have previously signed in and are stored in the cache. These accounts can be used later with `acquire_token_silent()` to find their associated tokens. ### Parameters * **username** (str) - Optional. Filters accounts by the provided username (case-insensitive). ### Returns A list of account objects. Each account object is a dictionary, and for now, only the "username" field is documented. ``` -------------------------------- ### acquire_token_by_device_flow Source: https://msal-python.readthedocs.io/en/latest Obtains a token using a device flow object, allowing for customizable polling effects. The polling can be controlled by modifying the 'expires_at' value within the flow dictionary. ```APIDOC ## acquire_token_by_device_flow ### Description Obtains a token using a device flow object, allowing for customizable polling effects. The polling can be controlled by modifying the 'expires_at' value within the flow dictionary. ### Method acquire_token_by_device_flow ### Parameters #### Parameters * **flow** (dict) - A dictionary previously generated by `initiate_device_flow()`. The polling effect blocks the current thread by default. To abort polling, set `flow['expires_at']` to 0. * **claims_challenge** (string, optional) - Additional claims challenge for the token request. * **kwargs** - Additional keyword arguments. ``` -------------------------------- ### SerializableTokenCache Class Source: https://msal-python.readthedocs.io/en/latest SerializableTokenCache extends TokenCache and provides methods for serializing and deserializing the cache state. It includes a flag to track state changes. ```APIDOC ## SerializableTokenCache Class ### Description This class provides methods for serializing and deserializing the cache state. This serialization can be a starting point to implement your own persistence. This class does NOT actually persist the cache on disk/db/etc. ### Variables - **has_state_changed** (bool) – Indicates whether the cache state in the memory has changed since last `serialize()` or `deserialize()` call. ### Methods #### add(_event_, **kwargs) - **Description**: Handle a token obtaining event, and add tokens into cache. #### deserialize(_state: str | None_) → None - **Description**: Deserialize the cache from a state previously obtained by serialize(). #### serialize() → str - **Description**: Serialize the current cache state into a string. ``` -------------------------------- ### ConfidentialClientApplication Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Represents a confidential client application, such as a web app or a service, that can securely store a client secret. ```APIDOC ## ConfidentialClientApplication ### Description Represents a confidential client application, such as a web app or a service, that can securely store a client secret. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### acquire_token_by_authorization_code Source: https://msal-python.readthedocs.io/en/latest Completes the Authorization Code Grant by exchanging the authorization code for tokens. Requires the authorization code and scopes. ```APIDOC ## acquire_token_by_authorization_code ### Description This is the second half of the Authorization Code Grant. It exchanges the authorization code received from the Authorization Server for tokens. ### Method `acquire_token_by_authorization_code(code, scopes, redirect_uri=None, nonce=None, claims_challenge=None, **kwargs)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **code** (string) - Required - The authorization code returned from the Authorization Server. * **scopes** (list[str]) - Required - Scopes requested to access a protected API (a resource). * **redirect_uri** (string) - Optional - The redirect URI used in the initial authorization request. * **nonce** (string) - Optional - A nonce value to prevent replay attacks. * **claims_challenge** (string) - Optional - A claims challenge to be included in the token request. * **kwargs** - Additional keyword arguments. ### Request Example ```python result = app.acquire_token_by_authorization_code( code="AUTHORIZATION_CODE", scopes=["api://your-api/read"], redirect_uri="YOUR_REDIRECT_URI" ) ``` ### Response #### Success Response (200) * **dict** - A dictionary containing "access_token" and/or "id_token", among others, depending on what scope was used. (See https://tools.ietf.org/html/rfc6749#section-5.1) ``` -------------------------------- ### TokenCache Source: https://msal-python.readthedocs.io/en/latest/_sources/index.rst.txt Manages the caching of tokens for client applications. Can be subclassed for custom serialization. ```APIDOC ## TokenCache ### Description Manages the caching of tokens for client applications. Can be subclassed for custom serialization. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```