Freigeben über


PublicClientApplication Class

Same as <xref:ClientApplication.__init__>, except that client_credential parameter shall remain None.

Note

You may set enable_broker_on_windows and/or enable_broker_on_mac to True.

What is a broker, and why use it?

A broker is a component installed on your device.

Broker implicitly gives your device an identity. By using a broker,

your device becomes a factor that can satisfy MFA (Multi-factor authentication).

This factor would become mandatory

if a tenant's admin enables a corresponding Conditional Access (CA) policy.

The broker's presence allows Microsoft identity platform

to have higher confidence that the tokens are being issued to your device,

and that is more secure.

An additional benefit of broker is,

it runs as a long-lived process with your device's OS,

and maintains its own cache,

so that your broker-enabled apps (even a CLI)

could automatically SSO from a previously established signed-in session.

You shall only enable broker when your app:

is running on supported platforms,

and already registered their corresponding redirect_uri

ms-appx-web://Microsoft.AAD.BrokerPlugin/your_client_id

if your app is expected to run on Windows 10+

msauth.com.msauth.unsignedapp://auth

if your app is expected to run on Mac

installed broker dependency,

e.g. pip install msal[broker]>=1.31,<2.

tested with acquire_token_interactive() and acquire_token_silent().

The fallback behaviors of MSAL Python's broker support

MSAL will either error out, or silently fallback to non-broker flows.

MSAL will ignore the enable_broker_... and bypass broker

on those auth flows that are known to be NOT supported by broker.

This includes ADFS, B2C, etc..

For other "could-use-broker" scenarios, please see below.

MSAL errors out when app developer opted-in to use broker

but a direct dependency "mid-tier" package is not installed.

Error message guides app developer to declare the correct dependency

msal[broker].

We error out here because the error is actionable to app developers.

MSAL silently "deactivates" the broker and fallback to non-broker,

when opted-in, dependency installed yet failed to initialize.

We anticipate this would happen on a device whose OS is too old

or the underlying broker component is somehow unavailable.

There is not much an app developer or the end user can do here.

Eventually, the conditional access policy shall

force the user to switch to a different device.

MSAL errors out when broker is opted in, installed, initialized,

but subsequent token request(s) failed.

Inheritance
PublicClientApplication

Constructor

PublicClientApplication(client_id, client_credential=None, **kwargs)

Parameters

Name Description
enable_broker_on_windows
Required
<xref:boolean>

This setting is only effective if your app is running on Windows 10+. This parameter defaults to None, which means MSAL will not utilize a broker.

New in MSAL Python 1.25.0.

enable_broker_on_mac
Required
<xref:boolean>

This setting is only effective if your app is running on Mac. This parameter defaults to None, which means MSAL will not utilize a broker.

New in MSAL Python 1.31.0.

client_id
Required
client_credential
Default value: None

Methods

acquire_token_by_device_flow

Obtain token by a device flow object, with customizable polling effect.

acquire_token_interactive

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

initiate_device_flow

Initiate a Device Flow instance, which will be used in acquire_token_by_device_flow.

acquire_token_by_device_flow

Obtain token by a device flow object, with customizable polling effect.

acquire_token_by_device_flow(flow, claims_challenge=None, **kwargs)

Parameters

Name Description
flow
Required

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.

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_interactive

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

acquire_token_interactive(scopes, prompt=None, login_hint=None, domain_hint=None, claims_challenge=None, timeout=None, port=None, extra_scopes_to_consent=None, max_age=None, parent_window_handle=None, on_before_launching_ui=None, auth_scheme=None, **kwargs)

Parameters

Name Description
scopes
Required

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 <xref:msal.Prompt>.

Default value: None
login_hint
str

Optional. Identifier of the user. Generally a User Principal Name (UPN).

Default value: None
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 available in Auth Code Flow doc and domain_hint doc.

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

This method will block the current thread. This parameter specifies the timeout value in seconds. Default value None means wait indefinitely.

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

Default value: None
extra_scopes_to_consent

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

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

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

Default value: None
on_before_launching_ui
<xref:function>

A callback with the form of lambda ui="xyz", **kwargs: print("A {} will be launched".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.

Default value: None
auth_scheme

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.

Default value: None

Returns

Type Description
  • A dict containing no "error" key, and typically contains an "access_token" key.

  • A dict containing an "error" key, when token refresh failed.

initiate_device_flow

Initiate a Device Flow instance, which will be used in acquire_token_by_device_flow.

initiate_device_flow(scopes=None, **kwargs)

Parameters

Name Description
scopes

Scopes requested to access a protected API (a resource).

Default value: None

Returns

Type Description

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.

Attributes

CONSOLE_WINDOW_HANDLE

CONSOLE_WINDOW_HANDLE = <object object>

DEVICE_FLOW_CORRELATION_ID

DEVICE_FLOW_CORRELATION_ID = '_correlation_id'