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

Name Description
client_id
Required
str

Your app has a client_id after you register it on Microsoft Entra admin center.

client_credential

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) formatFeed in a dict in this form:


   {
       "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
       "thumbprint": "A1B2C3D4E5F6...",
       "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 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.

Support Subject Name/Issuer Auth with a cert in .pemSubject Name/Issuer Auth

is an approach to allow easier certificate rotation.Added in version 0.5.0:


   {
       "private_key": "...-----BEGIN PRIVATE KEY-----... in PEM format",
       "thumbprint": "A1B2C3D4E5F6...",
       "public_certificate": "...-----BEGIN CERTIFICATE-----...",
       "passphrase": "Passphrase if the private_key is encrypted (Optional. Added in version 1.6.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.

Supporting raw assertion obtained from elsewhereAdded 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..."
   }

Supporting reading client cerficates from PFX filesAdded in version 1.29.0:

Feed in a dictionary containing the path to a PFX file:


   {
       "private_key_pfx_path": "/path/to/your.pfx",
       "passphrase": "Passphrase if the private_key is encrypted (Optional)",
   }

The following command will generate a .pfx file from your .key and .pem file:


   openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.pem

Support Subject Name/Issuer Auth with a cert in .pfxAdded in version 1.30.0:

If your .pfx file contains both the private key and public cert, you can opt in for Subject Name/Issuer Auth like this:


   {
       "private_key_pfx_path": "/path/to/your.pfx",
       "public_certificate": True,
       "passphrase": "Passphrase if the private_key is encrypted (Optional)",
   }
Default value: None
client_claims

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
   }
Default value: None
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, ...)
Default value: None
validate_authority

(optional) Turns authority validation on or off. This parameter default to true.

Default value: True
token_cache

Sets the token cache used by this ClientApplication instance. By default, an in-memory cache will be created and used.

Default value: None
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.

Default value: None
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

Default value: True
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

Default value: None
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

Default value: None
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.

Default value: None
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.

Default value: None
client_capabilities

(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 may issue Continuous Access Evaluation (CAE) access tokens to resources, knowing that when the resource emits a claims challenge the client will be able to handle those challenges.

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.

Default value: None
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://video2.skills-academy.com/entra/msal/dotnet/resources/region-discovery-troubleshooting

New in version 1.12.0.

Default value: None
exclude_scopes

(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"].

Default value: None
http_cache

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.

Default value: None
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.

Default value: None
allow_broker
<xref:boolean>

Deprecated. Please use enable_broker_on_windows instead.

Default value: None
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.

Default value: None
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.

Default value: None

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

Name Description
scopes
Required

(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.

Default value: None

Returns

Type Description

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

Name Description
user_assertion
Required
str

The incoming token already received by this app

scopes
Required

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.

Default value: None

Returns

Type Description

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()