Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Anthropics Anthropic sdk python Cloud Provider Auth

From Leeroopedia
Knowledge Sources
Domains Cloud_Deployment, LLM, Infrastructure
Last Updated 2026-02-15 00:00 GMT

Overview

This page documents the provider-specific authentication implementations used by the Anthropic Python SDK's cloud provider clients. Each provider follows a distinct authentication protocol while sharing a common pattern of constructor argument resolution with environment variable fallbacks.

Type: Pattern Doc

Source:

  • Bedrock: src/anthropic/lib/bedrock/_client.py:L136-159
  • Vertex: src/anthropic/lib/vertex/_client.py:L94-141
  • Foundry: src/anthropic/lib/foundry.py:L121-174

AWS Bedrock Authentication

Constructor Parameters

from anthropic import AnthropicBedrock

client = AnthropicBedrock(
    aws_secret_key="...",       # AWS secret access key
    aws_access_key="...",       # AWS access key ID
    aws_region="us-east-1",     # AWS region (auto-inferred if omitted)
    aws_profile="my-profile",   # Named AWS CLI profile
    aws_session_token="...",    # Session token for temporary credentials
)

Region Inference

If aws_region is not provided, the SDK's _infer_region() function resolves it in order:

  1. AWS_REGION environment variable
  2. boto3.Session().region_name (from AWS config files or instance metadata)
  3. Falls back to "us-east-1" with a warning

SigV4 Request Signing

The _prepare_request() method calls get_auth_headers() from src/anthropic/lib/bedrock/_auth.py, which:

  1. Creates a boto3.Session from the provided credentials (cached via @lru_cache).
  2. Extracts credentials via session.get_credentials().
  3. Creates a botocore.auth.SigV4Auth signer for the "bedrock" service.
  4. Signs the request using signer.add_auth(request).
  5. Returns the signed headers (Authorization, X-Amz-Date, X-Amz-Security-Token).
# From src/anthropic/lib/bedrock/_auth.py
def get_auth_headers(
    *,
    method: str,
    url: str,
    headers: httpx.Headers,
    aws_access_key: str | None,
    aws_secret_key: str | None,
    aws_session_token: str | None,
    region: str | None,
    profile: str | None,
    data: str | None,
) -> dict[str, str]:
    from botocore.auth import SigV4Auth
    from botocore.awsrequest import AWSRequest

    session = _get_session(
        profile=profile, region=region,
        aws_access_key=aws_access_key,
        aws_secret_key=aws_secret_key,
        aws_session_token=aws_session_token,
    )
    headers = headers.copy()
    del headers["connection"]

    request = AWSRequest(method=method.upper(), url=url, headers=headers, data=data)
    credentials = session.get_credentials()
    signer = SigV4Auth(credentials, "bedrock", session.region_name)
    signer.add_auth(request)
    prepped = request.prepare()
    return {key: value for key, value in dict(prepped.headers).items() if value is not None}

Base URL Resolution

  1. Constructor base_url argument
  2. ANTHROPIC_BEDROCK_BASE_URL environment variable
  3. Default: https://bedrock-runtime.{aws_region}.amazonaws.com

Google Cloud Vertex AI Authentication

Constructor Parameters

from anthropic import AnthropicVertex

client = AnthropicVertex(
    region="us-east5",           # Required (or CLOUD_ML_REGION env var)
    project_id="my-project",     # GCP project ID (or ANTHROPIC_VERTEX_PROJECT_ID)
    access_token="ya29.xxx",     # Explicit OAuth2 token (optional)
    credentials=creds_obj,       # GoogleCredentials object (optional)
)

Token Resolution Flow

The _ensure_access_token() method resolves authentication in order:

  1. If access_token was provided, use it directly.
  2. If a credentials object was provided, refresh it if expired and extract credentials.token.
  3. Otherwise, call google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) to load Application Default Credentials.
# From src/anthropic/lib/vertex/_client.py
def _ensure_access_token(self) -> str:
    if self.access_token is not None:
        return self.access_token

    if not self.credentials:
        self.credentials, project_id = load_auth(project_id=self.project_id)
        if not self.project_id:
            self.project_id = project_id

    if self.credentials.expired or not self.credentials.token:
        refresh_auth(self.credentials)

    if not self.credentials.token:
        raise RuntimeError("Could not resolve API token from the environment")

    return self.credentials.token

The token is injected as Authorization: Bearer {token} in _prepare_request(). If the request already has an Authorization header, the method is a no-op.

Async Considerations

In AsyncAnthropicVertex, the blocking load_auth() and refresh_auth() calls are wrapped with asyncify() to run them in a thread pool, preventing event loop blocking.

Base URL Resolution

  1. Constructor base_url argument
  2. ANTHROPIC_VERTEX_BASE_URL environment variable
  3. Default for global region: https://aiplatform.googleapis.com/v1
  4. Default for other regions: https://{region}-aiplatform.googleapis.com/v1

Azure AI Foundry Authentication

Constructor Parameters

from anthropic import AnthropicFoundry

# Option 1: API key
client = AnthropicFoundry(
    resource="my-resource",      # Azure resource name
    api_key="...",               # Or ANTHROPIC_FOUNDRY_API_KEY env var
)

# Option 2: Azure AD token provider
client = AnthropicFoundry(
    resource="my-resource",
    azure_ad_token_provider=lambda: get_token(),  # Called on every request
)

Authentication Flow

The _prepare_options() method handles authentication by checking in order:

  1. If an azure_ad_token_provider was provided, invoke it and set Authorization: Bearer {token}.
  2. If an api_key was provided, set the api-key header (note: this is the Azure convention, not x-api-key).
  3. If neither is provided, construction raises AnthropicError.
# From src/anthropic/lib/foundry.py
def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
    headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {}
    options = model_copy(options)
    options.headers = headers

    azure_ad_token = self._get_azure_ad_token()
    if azure_ad_token is not None:
        if headers.get("Authorization") is None:
            headers["Authorization"] = f"Bearer {azure_ad_token}"
    elif self.api_key is not None:
        if headers.get("api-key") is None:
            headers["api-key"] = self.api_key
    else:
        raise ValueError("Unable to handle auth")

    return options

Mutual Exclusivity

While the runtime does not explicitly block providing both api_key and azure_ad_token_provider, the MutuallyExclusiveAuthError class is defined for this case. The Azure AD token takes precedence when both are present.

Base URL Resolution

  1. Constructor base_url argument (mutually exclusive with resource)
  2. ANTHROPIC_FOUNDRY_BASE_URL environment variable
  3. Default: https://{resource}.services.ai.azure.com/anthropic/
  4. The resource parameter is read from ANTHROPIC_FOUNDRY_RESOURCE if not provided

Environment Variable Summary

Provider Variable Purpose
Bedrock AWS_REGION AWS region fallback
Bedrock ANTHROPIC_BEDROCK_BASE_URL Custom base URL
Vertex CLOUD_ML_REGION Region (required if not passed)
Vertex ANTHROPIC_VERTEX_PROJECT_ID GCP project ID
Vertex ANTHROPIC_VERTEX_BASE_URL Custom base URL
Foundry ANTHROPIC_FOUNDRY_API_KEY API key
Foundry ANTHROPIC_FOUNDRY_RESOURCE Azure resource name
Foundry ANTHROPIC_FOUNDRY_BASE_URL Custom base URL

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment