Welcome to MSAL Python’s documentation!¶
You can find high level conceptual documentations in the project README and workable samples inside the project code base .
The documentation hosted here is for API Reference.
PublicClientApplication and ConfidentialClientApplication¶
MSAL proposes a clean separation between public client applications and confidential client applications.
They are implemented as two separated classes, with different methods for different authentication scenarios.
PublicClientApplication¶
-
class
msal.
PublicClientApplication
(client_id, client_credential=None, **kwargs)¶ -
acquire_token_by_device_flow
(flow, claims_challenge=None, **kwargs)¶ Obtain token by a device flow object, with customizable polling effect.
Parameters: - flow (dict) – A dict previously generated by
initiate_device_flow()
. By default, this method’s polling effect will block current thread. You can abort the polling loop at any time, by changing the value of the flow’s “expires_at” key to 0. - 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.
Returns: A dict representing the json response from AAD:
- A successful response would contain “access_token” key,
- an error response would contain “error” and usually “error_description”.
- flow (dict) – A dict previously generated by
-
acquire_token_by_username_password
(username, password, scopes, claims_challenge=None, **kwargs)¶ 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: - 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.
Returns: A dict representing the json response from AAD:
- A successful response would contain “access_token” key,
- an error response would contain “error” and usually “error_description”.
-
acquire_token_interactive
(scopes, prompt=None, login_hint=None, domain_hint=None, claims_challenge=None, timeout=None, port=None, extra_scopes_to_consent=None, **kwargs)¶ Acquire token interactively i.e. via a local browser.
Parameters: - scope (list) – It is a list of case-sensitive strings.
- prompt (str) – By default, no prompt value will be sent, not even “none”. You will have to specify a value explicitly. Its valid values are defined in Open ID Connect specs https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
- login_hint (str) – Optional. Identifier of the user. Generally a User Principal Name (UPN).
- domain_hint –
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 here and here.
- 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.
- 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 AAD. 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.
Returns: - A dict containing no “error” key, and typically contains an “access_token” key, if cache lookup succeeded.
- A dict containing an “error” key, when token refresh failed.
-
initiate_device_flow
(scopes=None, **kwargs)¶ Initiate a Device Flow instance, which will be used in
acquire_token_by_device_flow()
.Parameters: scopes (list[str]) – Scopes requested to access a protected API (a resource). Returns: A dict representing a newly created Device Flow object. - A successful response would contain “user_code” key, among others
- an error response would contain some other readable key/value pairs.
-
ConfidentialClientApplication¶
-
class
msal.
ConfidentialClientApplication
(client_id, client_credential=None, authority=None, validate_authority=True, token_cache=None, http_client=None, verify=True, proxies=None, timeout=None, client_claims=None, app_name=None, app_version=None, client_capabilities=None)¶ -
acquire_token_for_client
(scopes, claims_challenge=None, **kwargs)¶ Acquires token for the current confidential client, not for an end user.
Parameters: - scopes (list[str]) – (Required) 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.
Returns: A dict representing the json response from AAD:
- A successful response would contain “access_token” key,
- an error response would contain “error” and usually “error_description”.
-
acquire_token_on_behalf_of
(user_assertion, scopes, claims_challenge=None, **kwargs)¶ 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. See detail docs here .
The current middle-tier app has no user interaction to obtain consent. See how to gain consent upfront for your middle-tier app from this article. https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
Parameters: - user_assertion (str) – The incoming token already received by this app
- scopes (list[str]) – Scopes required by downstream 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.
Returns: A dict representing the json response from AAD:
- A successful response would contain “access_token” key,
- an error response would contain “error” and usually “error_description”.
-
TokenCache¶
One of the parameter accepted by both PublicClientApplication and ConfidentialClientApplication is the TokenCache.
-
class
msal.
TokenCache
¶ This is considered as a base class containing minimal cache behavior.
Although it maintains tokens using unified schema across all MSAL libraries, this class does not serialize/persist them. See subclass
SerializableTokenCache
for details on serialization.-
add
(event, now=None)¶ Handle a token obtaining event, and add tokens into cache.
Known side effects: This function modifies the input event in place.
-
You can subclass it to add new behavior, such as, token serialization. See SerializableTokenCache for example.
-
class
msal.
SerializableTokenCache
¶ This serialization can be a starting point to implement your own persistence.
This class does NOT actually persist the cache on disk/db/etc.. Depending on your need, the following simple recipe for file-based persistence may be sufficient:
import os, atexit, msal cache = msal.SerializableTokenCache() if os.path.exists("my_cache.bin"): cache.deserialize(open("my_cache.bin", "r").read()) atexit.register(lambda: open("my_cache.bin", "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) ...
Variables: has_state_changed (bool) – Indicates whether the cache state in the memory has changed since last serialize()
ordeserialize()
call.-
add
(event, **kwargs)¶ Handle a token obtaining event, and add tokens into cache.
Known side effects: This function modifies the input event in place.
-
deserialize
(state)¶ Deserialize the cache from a state previously obtained by serialize()
-
serialize
()¶ Serialize the current cache state into a string.
-