ConfidentialClientApplication Class
Same as <xref:ClientApplication.__init__>,
except that allow_broker
parameter shall remain None
.
Create an instance of application.
- Inheritance
-
ConfidentialClientApplication
Constructor
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, azure_region=None, exclude_scopes=None, http_cache=None, instance_discovery=None, allow_broker=None, enable_pii_log=None, oidc_authority=None)
Parameters
- client_id
- str
Your app has a client_id after you register it on Microsoft Entra admin center.
For PublicClientApplication, you use None here. For ConfidentialClientApplication, it can be a string containing client secret, or an X509 certificate container in this form:
{
"private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
"thumbprint": "A1B2C3D4E5F6...",
"public_certificate": "...-----BEGIN CERTIFICATE-----... (Optional. See below.)",
"passphrase": "Passphrase if the private_key is encrypted (Optional. Added in version 1.6.0)",
}
MSAL Python requires a "private_key" in PEM format. If your cert is in a PKCS12 (.pfx) format, you can also convert it to PEM and get the thumbprint.
The thumbprint is available in your app's registration in Azure Portal. Alternatively, you can calculate the thumbprint.
Added in version 0.5.0: public_certificate (optional) is public key certificate which will be sent through 'x5c' JWT header only for subject name and issuer authentication to support cert auto rolls.
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.
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..."
}
- client_claims
- dict
Added in version 0.5.0: It is a dictionary of extra claims that would be signed by by this ConfidentialClientApplication 's private key. For example, you can use {"client_ip": "x.x.x.x"}. You may also override any of the following default claims:
{
"aud": the_token_endpoint,
"iss": self.client_id,
"sub": same_as_issuer,
"exp": now + 10_min,
"iat": now,
"jti": a_random_uuid
}
- authority
- str
A URL that identifies a token authority. It should be of the format
https://login.microsoftonline.com/your_tenant
By default, we will use https://login.microsoftonline.com/common
Changed in version 1.17: you can also use predefined constant and a builder like this:
from msal.authority import (
AuthorityBuilder,
AZURE_US_GOVERNMENT, AZURE_CHINA, AZURE_PUBLIC)
my_authority = AuthorityBuilder(AZURE_PUBLIC, "contoso.onmicrosoft.com")
# Now you get an equivalent of
# "https://login.microsoftonline.com/contoso.onmicrosoft.com"
# You can feed such an authority to msal's ClientApplication
from msal import PublicClientApplication
app = PublicClientApplication("my_client_id", authority=my_authority, ...)
- validate_authority
- bool
(optional) Turns authority validation on or off. This parameter default to true.
- token_cache
- TokenCache
Sets the token cache used by this ClientApplication instance. By default, an in-memory cache will be created and used.
- http_client
(optional) Your implementation of abstract class HttpClient <msal.oauth2cli.http.http_client> Defaults to a requests session instance. Since MSAL 1.11.0, the default session would be configured to attempt one retry on connection error. If you are providing your own http_client, it will be your http_client's duty to decide whether to perform retry.
- verify
(optional) It will be passed to the verify parameter in the underlying requests library This does not apply if you have chosen to pass your own Http client
- proxies
(optional) It will be passed to the proxies parameter in the underlying requests library This does not apply if you have chosen to pass your own Http client
- timeout
(optional) It will be passed to the timeout parameter in the underlying requests library This does not apply if you have chosen to pass your own Http client
- app_name
(optional) You can provide your application name for Microsoft telemetry purposes. Default value is None, means it will not be passed to Microsoft.
- app_version
(optional) You can provide your application version for Microsoft telemetry purposes. Default value is None, means it will not be passed to Microsoft.
(optional) Allows configuration of one or more client capabilities, e.g. ["CP1"].
Client capability is meant to inform the Microsoft identity platform (STS) what this client is capable for, so STS can decide to turn on certain features. For example, if client is capable to handle claims challenge, STS can then issue CAE access tokens to resources knowing when the resource emits claims challenge the client will be capable to handle.
Implementation details: Client capability is implemented using "claims" parameter on the wire, for now. MSAL will combine them into claims parameter which you will later provide via one of the acquire-token request.
- azure_region
- str
(optional)
Instructs MSAL to use the Entra regional token service. This legacy feature is only available to
first-party applications. Only acquire_token_for_client()
is supported.
Supports 3 values:
azure_region=None
- meaning no region is used. This is the default value.
azure_region="some_region"
- meaning the specified region is used.
azure_region=True
- meaning MSAL will try to auto-detect the region. This is not recommended.
Note
Region auto-discovery has been tested on VMs and on Azure Functions. It is unreliable.
Applications using this option should configure a short timeout.
For more details and for the values of the region string
see https://learn.microsoft.com/entra/msal/dotnet/resources/region-discovery-troubleshooting
New in version 1.12.0.
(optional)
Historically MSAL hardcodes offline_access scope,
which would allow your app to have prolonged access to user's data.
If that is unnecessary or undesirable for your app,
now you can use this parameter to supply an exclusion list of scopes,
such as exclude_scopes = ["offline_access"]
.
- http_cache
- dict
MSAL has long been caching tokens in the token_cache
.
Recently, MSAL also introduced a concept of http_cache
,
by automatically caching some finite amount of non-token http responses,
so that long-lived
PublicClientApplication
and ConfidentialClientApplication
would be more performant and responsive in some situations.
This http_cache
parameter accepts any dict-like object.
If not provided, MSAL will use an in-memory dict.
If your app is a command-line app (CLI), you would want to persist your http_cache across different CLI runs. The following recipe shows a way to do so:
# Just add the following lines at the beginning of your CLI script
import sys, atexit, pickle
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
):
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")))
# And then you can implement your app as you normally would
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"], ...)
Content inside http_cache
are cheap to obtain.
There is no need to share them among different apps.
Content inside http_cache
will contain no tokens nor
Personally Identifiable Information (PII). Encryption is unnecessary.
New in version 1.16.0.
- instance_discovery
- <xref:boolean>
Historically, MSAL would connect to a central endpoint located at
https://login.microsoftonline.com
to acquire some metadata,
especially when using an unfamiliar authority.
This behavior is known as Instance Discovery.
This parameter defaults to None, which enables the Instance Discovery.
If you know some authorities which you allow MSAL to operate with as-is, without involving any Instance Discovery, the recommended pattern is:
known_authorities = frozenset([ # Treat your known authorities as const
"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,
)
If you do not know some authorities beforehand,
yet still want MSAL to accept any authority that you will provide,
you can use a False
to unconditionally disable Instance Discovery.
New in version 1.19.0.
- allow_broker
- <xref:boolean>
Deprecated. Please use enable_broker_on_windows
instead.
- enable_pii_log
- <xref:boolean>
When enabled, logs may include PII (Personal Identifiable Information). This can be useful in troubleshooting broker behaviors. The default behavior is False.
New in version 1.24.0.
- oidc_authority
- str
Added in version 1.28.0:
It is a URL that identifies an OpenID Connect (OIDC) authority of
the format https://contoso.com/tenant
.
MSAL will append ".well-known/openid-configuration" to the authority
and retrieve the OIDC metadata from there, to figure out the endpoints.
Note: Broker will NOT be used for OIDC authority.
Methods
acquire_token_for_client |
Acquires token for the current confidential client, not for an end user. Since MSAL Python 1.23, it will automatically look for token from cache, and only send request to Identity Provider when cache misses. |
acquire_token_on_behalf_of |
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 |
remove_tokens_for_client |
Remove all tokens that were previously acquired via acquire_token_for_client for the current client. |
acquire_token_for_client
Acquires token for the current confidential client, not for an end user.
Since MSAL Python 1.23, it will automatically look for token from cache, and only send request to Identity Provider when cache misses.
acquire_token_for_client(scopes, claims_challenge=None, **kwargs)
Parameters
- 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 Microsoft Entra:
A successful response would contain "access_token" key,
an error response would contain "error" and usually "error_description".
acquire_token_on_behalf_of
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
acquire_token_on_behalf_of(user_assertion, scopes, claims_challenge=None, **kwargs)
Parameters
- 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 Microsoft Entra:
A successful response would contain "access_token" key,
an error response would contain "error" and usually "error_description".
remove_tokens_for_client
Remove all tokens that were previously acquired via acquire_token_for_client for the current client.
remove_tokens_for_client()
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for