Authentication functionality for a variety of services.
Functions¶
caller_principal_context¶
caller_principal_context(principal: str | None) → contextvars.ContextCopy the current context with an explicit caller principal.
Pass the result as context to asyncio.create_task when work captured for one
caller is started from another caller’s context, such as a queued run.
| Parameter | Type | Description |
|---|---|---|
principal | str | None | Stable key of the caller the work belongs to. |
Returns:
contextvars.Context— contextvars.Context: A copy of the current context with the principal replaced.
caller_principal_scope¶
caller_principal_scope(principal: str | None) → Generator[None, None, None]Run work on behalf of one caller, or of no caller when principal is None.
Tasks created inside the scope inherit the principal.
| Parameter | Type | Description |
|---|---|---|
principal | str | None | Stable key of the caller. |
clean_credential_value¶
clean_credential_value(value: str, name: str) → strStrip surrounding whitespace from a credential and refuse one that can’t be sent.
| Parameter | Type | Description |
|---|---|---|
value | str | The credential, such as an API key or a header value. |
name | str | What the value is for, such as "api_key" or a header name, for errors. |
Returns:
str— The credential without surrounding whitespace.
Raises:
ValueError— If the credential is blank, contains non-ASCII text, or contains a control character.
clean_request_headers¶
clean_request_headers(headers: Mapping[str, str]) → dict[str, str]Check header names and values, trimming surrounding whitespace.
An empty value and a tab inside a value are allowed, since HTTP allows them.
| Parameter | Type | Description |
|---|---|---|
headers | Mapping[str, str] | Header names and values. |
Returns:
dict[str, str]— dict[str, str]: The headers with surrounding whitespace removed from names and values.
Raises:
ValueError— If a name isn’t a valid header name, or a value contains non-ASCII text or a control character.
ensure_async_token_provider¶
ensure_async_token_provider(api_key: str | Callable[[], str | Awaitable[str]] | None) → str | Callable[[], Awaitable[str]] | NoneEnsure the api_key is either a string or an async callable.
If a synchronous callable token provider is provided, it’s automatically wrapped in an async function to make it compatible with async Azure SDK clients.
| Parameter | Type | Description |
|---|---|---|
api_key | str | Callable[[], str | Awaitable[str]] | None | Either a string API key or a callable that returns a token (sync or async). |
Returns:
str | Callable[[], Awaitable[str]] | None— Either a string API key or an async callable that returns a token.
get_azure_async_token_provider¶
get_azure_async_token_provider(scope: str) → Callable[[], Awaitable[str]]Get an asynchronous Azure token provider using AsyncDefaultAzureCredential.
Returns an async callable suitable for use with async clients like OpenAI’s AsyncOpenAI. The callable handles automatic token refresh.
| Parameter | Type | Description |
|---|---|---|
scope | str | The Azure token scope (e.g., ‘https:// |
Returns:
Callable[[], Awaitable[str]]— Async callable that returns bearer tokens.
Examples:
get_azure_openai_auth¶
get_azure_openai_auth(endpoint: str) → Callable[[], Awaitable[str]]Get an async Azure token provider for OpenAI endpoints.
Automatically determines the correct scope based on the endpoint URL and returns an async token provider suitable for use with AsyncOpenAI clients.
| Parameter | Type | Description |
|---|---|---|
endpoint | str | The Azure OpenAI endpoint URL. |
Returns:
Callable[[], Awaitable[str]]— Async callable that returns bearer tokens.
Examples:
get_azure_token_provider¶
get_azure_token_provider(scope: str) → Callable[[], str]Get a synchronous Azure token provider using DefaultAzureCredential.
Returns a callable that returns a bearer token string. The callable handles automatic token refresh.
| Parameter | Type | Description |
|---|---|---|
scope | str | The Azure token scope (e.g., ‘https:// |
Returns:
Callable[[], str]— Callable[[], str]: A token provider function that returns bearer tokens.
Examples:
get_caller_principal¶
get_caller_principal() → str | NoneReturn the caller principal of the current context.
Returns:
str | None— str | None: The caller principal, or None when no caller is in scope.
get_default_azure_scope¶
get_default_azure_scope(endpoint: str) → strDetermine the appropriate Azure token scope based on the endpoint URL.
The Cognitive Services scope is accepted by all Azure AI endpoints including Azure OpenAI (.openai.azure.com) and AI Foundry (.ai.azure.com).
| Parameter | Type | Description |
|---|---|---|
endpoint | str | The Azure endpoint URL. |
Returns:
str— The token scope ‘https://cognitiveservices .azure .com / .default’.
get_lazy_dir¶
get_lazy_dir(module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → list[str]Return package attributes and unresolved public exports.
| Parameter | Type | Description |
|---|---|---|
module_globals | dict[str, Any] | The package globals. |
exports | Mapping[str, LazyExport] | Public names and their implementation locations. |
Returns:
list[str]— list[str]: Sorted package attribute names.
is_azure_ml_endpoint¶
is_azure_ml_endpoint(endpoint: str | None) → boolReturn True if endpoint resolves to a known AML managed online host.
Uses a strict hostname-suffix check (not a substring search).
| Parameter | Type | Description |
|---|---|---|
endpoint | str | None | The endpoint URL to validate. |
Returns:
bool— True if the endpoint’s hostname ends with a recognised AML suffix.
is_azure_openai_endpoint¶
is_azure_openai_endpoint(endpoint: str | None) → boolReturn True if endpoint resolves to a known Azure OpenAI / AI Foundry host.
Uses a strict hostname-suffix check (not a substring search) so an Entra ID token is only minted for a Microsoft-operated endpoint.
| Parameter | Type | Description |
|---|---|---|
endpoint | str | None | The endpoint URL to validate. |
Returns:
bool— True if the endpoint’s hostname ends with a recognised Azure suffix.
resolve_lazy_export¶
resolve_lazy_export(name: str, module_name: str, module_globals: dict[str, Any], exports: Mapping[str, LazyExport]) → AnyResolve and cache one package export.
| Parameter | Type | Description |
|---|---|---|
name | str | Public attribute requested from the package. |
module_name | str | Package name used in an AttributeError. |
module_globals | dict[str, Any] | Package globals where the resolved value is cached. |
exports | Mapping[str, LazyExport] | Public names and their implementation locations. |
Returns:
Any— The resolved public value.
Raises:
AttributeError— Ifnameis not a declared lazy export.
resolve_openai_auth¶
resolve_openai_auth(endpoint: str, api_key: str | Callable[[], str | Awaitable[str]] | None, api_key_environment_variable: str, auth_mode: AuthMode = 'api_key') → str | Callable[[], Awaitable[str]]Resolve OpenAI authentication from an explicit identity choice, a key, or an environment variable.
| Parameter | Type | Description |
|---|---|---|
endpoint | str | The OpenAI-compatible endpoint URL. |
api_key | str | Callable[[], str | Awaitable[str]] | None | The explicit API key or token provider. |
api_key_environment_variable | str | Environment variable to use when api_key is not provided. |
auth_mode | AuthMode | "identity" authenticates with a Microsoft Entra ID token minted for the endpoint; it ignores the API key environment variable and rejects an explicit api_key. "none" is for endpoints that need no key: it reads no key, rejects an explicit api_key and returns a fixed, non-secret placeholder because the OpenAI SDK requires one. "api_key" (the default) resolves a token-provider callable, then an explicit key, then the environment variable, and finally falls back to Entra ID on a recognized Azure OpenAI endpoint. That last fallback is deprecated and is removed in 1.4.0, after which identity auth must be requested explicitly. Defaults to 'api_key'. |
Returns:
str | Callable[[], Awaitable[str]]— str | Callable[[], Awaitable[str]]: API key string or async-compatible token provider.
Raises:
ValueError— If identity or no-key auth is requested alongside an explicitapi_key, if identity auth is requested for an endpoint that is not a recognized Azure OpenAI endpoint, or if"api_key"auth is requested and no key is available for an endpoint that is not a recognized Azure OpenAI endpoint.
AsyncTokenProviderCredential¶
Async wrapper to convert a token provider callable into an Azure AsyncTokenCredential.
This class bridges the gap between token provider functions (sync or async) and Azure SDK async clients that require an AsyncTokenCredential object (with async def get_token).
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
token_provider | Callable[[], str | Awaitable[str]] | A callable that returns a token string (sync) or an awaitable that returns a token string (async). Both are supported transparently. |
Methods:
close¶
close() → NoneNo-op close for protocol compliance. The callable provider does not hold resources.
get_token¶
get_token(scopes: str = (), kwargs: Any = {}) → AccessTokenGet an access token asynchronously.
| Parameter | Type | Description |
|---|---|---|
scopes | str | Token scopes (ignored as the scope is already configured in the token provider). Defaults to (). |
kwargs | Any | Additional arguments (ignored). Defaults to {}. |
Returns:
AccessToken— The access token with expiration time.
Authenticator¶
Bases: abc.ABC
Abstract base class for authenticators.
Methods:
get_token¶
get_token() → strGet the current authentication token synchronously.
Returns:
str— The current authentication token.
get_token_async¶
get_token_async() → strGet the current authentication token asynchronously.
Returns:
str— The current authentication token.
refresh_token¶
refresh_token() → strRefresh the authentication token synchronously.
Returns:
str— The refreshed authentication token.
refresh_token_async¶
refresh_token_async() → strRefresh the authentication token asynchronously.
Returns:
str— The refreshed authentication token.
AzureAuth¶
Bases: Authenticator
Azure CLI Authentication.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
token_scope | str | The token scope for authentication. |
tenant_id | str | The tenant ID to request the token for. If empty, the credential chain uses its default tenant. Defaults to “”. |
Methods:
get_token¶
get_token() → strGet the current token.
Returns:
str— current token
refresh_token¶
refresh_token() → strRefresh the access token if it is expired.
Returns:
str— A token
AzureStorageAuth¶
A utility class for Azure Storage authentication, providing methods to generate SAS tokens using user delegation keys.
Methods:
get_sas_token_async¶
get_sas_token_async(container_url: str) → strGenerate a SAS token for the specified blob using a user delegation key.
| Parameter | Type | Description |
|---|---|---|
container_url | str | The URL of the Azure Blob Storage container. |
Returns:
str— The generated SAS token.
Raises:
ValueError— If container_url is empty or invalid.
get_user_delegation_key_async¶
get_user_delegation_key_async(blob_service_client: BlobServiceClient) → UserDelegationKeyRetrieve a user delegation key valid for one day.
| Parameter | Type | Description |
|---|---|---|
blob_service_client | BlobServiceClient | An instance of BlobServiceClient to interact with Azure Blob Storage. |
Returns:
UserDelegationKey— A user delegation key valid for one day.
BrowserSessionCopilotAuthenticator¶
Bases: Authenticator
Acquire Microsoft Copilot access token from a browser session.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
profile_path | Path | None | Path to the persistent browser profile. If None, a default path is used. Defaults to None. |
token_capture_timeout_seconds | int | Timeout in seconds for capturing the token. Must be a positive integer. Defaults to DEFAULT_TOKEN_CAPTURE_TIMEOUT_SECONDS. |
expiry_buffer_seconds | int | Buffer time in seconds before token expiry. Must be a positive integer. Defaults to DEFAULT_EXPIRY_BUFFER_SECONDS. |
websocket_base_url | str | Valid wss URL prefix for token capture. The path is matched case-insensitively at a slash boundary. Defaults to wss://substrate.svc.cloud.microsoft/m365Copilot, covering both ChatHub and StreamHub connections. |
browser_channel | str | Browser channel to use for the session. Defaults to “msedge”. |
headless | bool | Whether to run the browser in headless mode. Defaults to False. |
copilot_url | str | URL for the Copilot chat interface. Must be a valid HTTPS URL. Defaults to DEFAULT_COPILOT_URL. |
Examples:
Methods:
close_async¶
close_async() → NoneDiscard authentication state and finish cleanup even if cancelled while waiting for token operations.
get_claims_async¶
get_claims_async() → dict[str, Any]Return the claims extracted from the current token.
get_token_async¶
get_token_async() → strReturn the current token, capturing a new one if necessary.
Returns:
str— The current access token as a string.
Raises:
ValueError— If captured token claims are missing, invalid, or within the expiry buffer.
refresh_token_async¶
refresh_token_async() → strForce a refresh of the current token, capturing a new one.
Returns:
str— The newly captured access token as a string.
CopilotAuthenticator¶
Bases: Authenticator
Playwright-based authenticator for Microsoft Copilot. Used by WebSocketCopilotTarget.
This authenticator automates browser login to obtain and refresh access tokens that are necessary for accessing Microsoft Copilot via WebSocket connections. It uses Playwright to simulate user interactions for authentication, and msal-extensions for encrypted token persistence.
An access token acquired by this authenticator is usually valid for about 60 minutes.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
headless | bool | Whether to run the browser in headless mode. Default is False. Defaults to False. |
maximized | bool | Whether to start the browser maximized. Default is True. Defaults to True. |
timeout_for_elements_seconds | int | Timeout used when waiting for page elements, in seconds. Defaults to DEFAULT_ELEMENT_TIMEOUT_SECONDS. |
token_capture_timeout_seconds | int | Maximum time to wait for token capture via network monitoring. Defaults to DEFAULT_TOKEN_CAPTURE_TIMEOUT. |
fallback_to_plaintext | bool | Whether to fallback to plaintext storage if encryption is unavailable. If set to False (default), an exception will be raised if encryption cannot be used. WARNING: Setting to True stores tokens in plaintext. |
Methods:
get_claims_async¶
get_claims_async() → dict[str, Any]Get the JWT claims from the current authentication token.
Returns:
dict[str, Any]— dict[str, Any]: The JWT claims decoded from the access token.
get_token_async¶
get_token_async() → strGet the current authentication token.
This checks the cache first and only launches the browser if no valid token is found. If multiple calls are made concurrently, they will be serialized via an asyncio lock to prevent launching multiple browser instances.
Returns:
str— A valid Bearer token for Microsoft Copilot.
refresh_token_async¶
refresh_token_async() → strRefresh the authentication token asynchronously.
This will clear the existing token cache and fetch a new token with automated browser login.
Returns:
str— The refreshed authentication token.
Raises:
RuntimeError— If token refresh fails.
ManualCopilotAuthenticator¶
Bases: Authenticator
Simple authenticator that uses a manually-provided access token for Microsoft Copilot.
This authenticator is useful for testing or environments where browser automation is not possible. Users can obtain the access token from browser DevTools and provide it directly.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
access_token | str | None | A valid JWT access token for Microsoft Copilot. This token can be obtained from browser DevTools when connected to Copilot. If None, the token will be read from the COPILOT_ACCESS_TOKEN environment variable. Defaults to None. |
Examples:
Methods:
get_claims_async¶
get_claims_async() → dict[str, Any]Get the JWT claims from the access token.
Returns:
dict[str, Any]— dict[str, Any]: The JWT claims decoded from the access token.
get_token¶
get_token() → strGet the current authentication token synchronously.
Returns:
str— The access token provided during initialization.
get_token_async¶
get_token_async() → strGet the current authentication token.
Returns:
str— The access token provided during initialization.
refresh_token¶
refresh_token() → strNot supported by this authenticator.
Raises:
RuntimeError— Always raised as manual tokens cannot be refreshed automatically.
refresh_token_async¶
refresh_token_async() → strNot supported by this authenticator.
Raises:
RuntimeError— Always raised as manual tokens cannot be refreshed automatically.
TokenProviderCredential¶
Wrapper to convert a token provider callable into an Azure TokenCredential.
This class bridges the gap between token provider functions (like those returned by get_azure_token_provider) and Azure SDK clients that require a TokenCredential object.
Constructor Parameters:
| Parameter | Type | Description |
|---|---|---|
token_provider | Callable[[], str | Callable[..., Any]] | A callable that returns either a token string or an awaitable that returns a token string. |
Methods:
get_token¶
get_token(scopes: str = (), kwargs: Any = {}) → AccessTokenGet an access token.
| Parameter | Type | Description |
|---|---|---|
scopes | str | Token scopes (ignored as the scope is already configured in the token provider). Defaults to (). |
kwargs | Any | Additional arguments (ignored). Defaults to {}. |
Returns:
AccessToken— The access token with expiration time.