Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

pyrit.auth

Authentication functionality for a variety of services.

Functions

ensure_async_token_provider

ensure_async_token_provider(api_key: str | Callable[[], str | Awaitable[str]] | None) → str | Callable[[], Awaitable[str]] | None

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

ParameterTypeDescription
api_key`strCallable[[], str

Returns:

get_azure_async_token_provider

get_azure_async_token_provider(scope: 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.

ParameterTypeDescription
scopestrThe Azure token scope (e.g., ‘https://cognitiveservices.azure.com/.default’).

Returns:

get_azure_openai_auth

get_azure_openai_auth(endpoint: 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.

ParameterTypeDescription
endpointstrThe Azure OpenAI endpoint URL.

Returns:

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.

ParameterTypeDescription
scopestrThe Azure token scope (e.g., ‘https://cognitiveservices.azure.com/.default’).

Returns:

get_default_azure_scope

get_default_azure_scope(endpoint: str) → str

Determine 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).

ParameterTypeDescription
endpointstrThe Azure endpoint URL.

Returns:

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:

ParameterTypeDescription
token_providerCallable[[], Union[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() → None

No-op close for protocol compliance. The callable provider does not hold resources.

get_token

get_token(scopes: str = (), kwargs: Any = {}) → AccessToken

Get an access token asynchronously.

ParameterTypeDescription
scopesstrToken scopes (ignored as the scope is already configured in the token provider). Defaults to ().
kwargsAnyAdditional arguments (ignored). Defaults to {}.

Returns:

Authenticator

Bases: abc.ABC

Abstract base class for authenticators.

Methods:

get_token

get_token() → str

Get the current authentication token synchronously.

Returns:

get_token_async

get_token_async() → str

Get the current authentication token asynchronously.

Returns:

refresh_token

refresh_token() → str

Refresh the authentication token synchronously.

Returns:

refresh_token_async

refresh_token_async() → str

Refresh the authentication token asynchronously.

Returns:

AzureAuth

Bases: Authenticator

Azure CLI Authentication.

Constructor Parameters:

ParameterTypeDescription
token_scopestrThe token scope for authentication.
tenant_idstrThe tenant ID. Defaults to “”. Defaults to ''.

Methods:

get_token

get_token() → str

Get the current token.

Returns:

refresh_token

refresh_token() → str

Refresh the access token if it is expired.

Returns:

AzureStorageAuth

A utility class for Azure Storage authentication, providing methods to generate SAS tokens using user delegation keys.

Methods:

get_sas_token

get_sas_token(container_url: str) → str

Generate a SAS token for the specified blob using a user delegation key.

ParameterTypeDescription
container_urlstrThe URL of the Azure Blob Storage container.

Returns:

Raises:

get_user_delegation_key

get_user_delegation_key(blob_service_client: BlobServiceClient) → UserDelegationKey

Retrieve a user delegation key valid for one day.

ParameterTypeDescription
blob_service_clientBlobServiceClientAn instance of BlobServiceClient to interact

Returns:

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:

ParameterTypeDescription
headlessboolWhether to run the browser in headless mode. Default is False. Defaults to False.
maximizedboolWhether to start the browser maximized. Default is True. Defaults to True.
timeout_for_elements_secondsintTimeout used when waiting for page elements, in seconds. Defaults to DEFAULT_ELEMENT_TIMEOUT_SECONDS.
token_capture_timeout_secondsintMaximum time to wait for token capture via network monitoring. Defaults to DEFAULT_TOKEN_CAPTURE_TIMEOUT.
network_retriesintNumber of retry attempts for network operations. Default is 3. Defaults to DEFAULT_NETWORK_RETRIES.
fallback_to_plaintextboolWhether 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. Defaults to False.

Methods:

get_claims

get_claims() → dict[str, Any]

Get the JWT claims from the current authentication token.

Returns:

get_token_async

get_token_async() → str

Get 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:

refresh_token_async

refresh_token_async() → str

Refresh the authentication token asynchronously.

This will clear the existing token cache and fetch a new token with automated browser login.

Returns:

Raises:

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:

ParameterTypeDescription
access_tokenOptional[str]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.

Methods:

get_claims

get_claims() → dict[str, Any]

Get the JWT claims from the access token.

Returns:

get_token

get_token() → str

Get the current authentication token synchronously.

Returns:

get_token_async

get_token_async() → str

Get the current authentication token.

Returns:

refresh_token

refresh_token() → str

Not supported by this authenticator.

Raises:

refresh_token_async

refresh_token_async() → str

Not supported by this authenticator.

Raises:

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:

ParameterTypeDescription
token_providerCallable[[], Union[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 = {}) → AccessToken

Get an access token.

ParameterTypeDescription
scopesstrToken scopes (ignored as the scope is already configured in the token provider). Defaults to ().
kwargsAnyAdditional arguments (ignored). Defaults to {}.

Returns: