共用方式為


ManagedIdentityClient Class

This API encapsulates multiple managed identity back-ends: VM, App Service, Azure Automation (Runbooks), Azure Function, Service Fabric, and Azure Arc.

It also provides token cache support.

Note

Cloud Shell support is NOT implemented in this class.

Since MSAL Python 1.18 in May 2022, it has been implemented in

<xref:PublicClientApplication.acquire_token_interactive> via calling pattern

PublicClientApplication(...).acquire_token_interactive(scopes=[...], prompt="none").

That is appropriate, because Cloud Shell yields a token with

delegated permissions for the end user who has signed in to the Azure Portal

(like what a PublicClientApplication does),

not a token with application permissions for an app.

Create a managed identity client.

Recipe 1: Hard code a managed identity for your app:


   import msal, requests
   client = msal.ManagedIdentityClient(
       msal.UserAssignedManagedIdentity(client_id="foo"),
       http_client=requests.Session(),
       )
   token = client.acquire_token_for_client("resource")

Recipe 2: Write once, run everywhere. If you use different managed identity on different deployment, you may use an environment variable (such as MY_MANAGED_IDENTITY_CONFIG) to store a json blob like {"ManagedIdentityIdType": "ClientId", "Id": "foo"} or {"ManagedIdentityIdType": "SystemAssignedManagedIdentity", "Id": null}). The following app can load managed identity configuration dynamically:


   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")
Inheritance
builtins.object
ManagedIdentityClient

Constructor

ManagedIdentityClient(managed_identity: dict | ManagedIdentity | SystemAssignedManagedIdentity | UserAssignedManagedIdentity, *, http_client, token_cache=None, http_cache=None)

Parameters

Name Description
managed_identity
Required

It accepts an instance of SystemAssignedManagedIdentity or UserAssignedManagedIdentity. They are equivalent to a dict with a certain shape, which may be loaded from a JSON configuration file or an env var.

http_client
Required

An http client object. For example, you can use requests.Session(), optionally with exponential backoff behavior demonstrated in this recipe:


   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)
token_cache
Required

Optional. It accepts a <xref:msal.TokenCache> instance to store tokens. It will use an in-memory token cache by default.

http_cache
Required

Optional. It has the same characteristics as the

:paramref:msal.ClientApplication.http_cache<<.

Keyword-Only Parameters

Name Description
http_client
Required
token_cache
Required
http_cache
Required

Methods

acquire_token_for_client

Acquire token for the managed identity.

The result will be automatically cached. Subsequent calls will automatically search from cache first.

Note

Known issue: When an Azure VM has only one user-assigned managed identity,

and your app specifies to use system-assigned managed identity,

Azure VM may still return a token for your user-assigned identity.

This is a service-side behavior that cannot be changed by this library.

Azure VM docs

acquire_token_for_client

Acquire token for the managed identity.

The result will be automatically cached. Subsequent calls will automatically search from cache first.

Note

Known issue: When an Azure VM has only one user-assigned managed identity,

and your app specifies to use system-assigned managed identity,

Azure VM may still return a token for your user-assigned identity.

This is a service-side behavior that cannot be changed by this library.

Azure VM docs

acquire_token_for_client(*, resource: str, claims_challenge: str | None = None)

Parameters

Name Description
resource
Required

The resource for which the token is acquired.

claims_challenge
Required

Optional. It is a string representation of a JSON object (which contains lists of claims being requested).

The tenant admin may choose to revoke all Managed Identity tokens, and then a claims challenge will be returned by the target resource, as a claims_challenge directive in the www-authenticate header, even if the app developer did not opt in for the "CP1" client capability. Upon receiving a claims_challenge, MSAL will skip a token cache read, and will attempt to acquire a new token.

Keyword-Only Parameters

Name Description
resource
Required
claims_challenge
Required