Implementation:Anthropics Anthropic sdk python Cloud Provider Auth
| 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:
AWS_REGIONenvironment variableboto3.Session().region_name(from AWS config files or instance metadata)- 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:
- Creates a
boto3.Sessionfrom the provided credentials (cached via@lru_cache). - Extracts credentials via
session.get_credentials(). - Creates a
botocore.auth.SigV4Authsigner for the"bedrock"service. - Signs the request using
signer.add_auth(request). - 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
- Constructor
base_urlargument ANTHROPIC_BEDROCK_BASE_URLenvironment variable- 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:
- If
access_tokenwas provided, use it directly. - If a
credentialsobject was provided, refresh it if expired and extractcredentials.token. - 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
- Constructor
base_urlargument ANTHROPIC_VERTEX_BASE_URLenvironment variable- Default for global region:
https://aiplatform.googleapis.com/v1 - 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:
- If an
azure_ad_token_providerwas provided, invoke it and setAuthorization: Bearer {token}. - If an
api_keywas provided, set theapi-keyheader (note: this is the Azure convention, notx-api-key). - 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
- Constructor
base_urlargument (mutually exclusive withresource) ANTHROPIC_FOUNDRY_BASE_URLenvironment variable- Default:
https://{resource}.services.ai.azure.com/anthropic/ - The
resourceparameter is read fromANTHROPIC_FOUNDRY_RESOURCEif 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 |