All articles

LLM API Authentication Across Providers: Keys, OAuth, Service Accounts, and Gateway Passthrough

A practical reference for authenticating to OpenAI, Anthropic, DashScope, DeepSeek, SiliconFlow, and Google Gemini APIs: header formats, OAuth/service-account options, gateway passthrough patterns, and common 401/403 failure modes.

· TheRouter

LLM API authentication looks simple until you run more than one provider in production. One vendor wants Authorization: Bearer ..., another wants x-api-key, Google can use API keys for Gemini API calls but OAuth/service accounts for Google Cloud paths, and enterprise admin endpoints often require a different credential class from inference endpoints.

This reference compares the authentication mechanics you actually need when wiring providers into SDKs, CI jobs, and an OpenAI-compatible gateway. It is deliberately scoped to auth method and request shape. For secret storage, rotation, and governance controls, pair it with our LLM API key management guide.

OpenAI-compatible means a provider exposes a chat-completions endpoint whose request and response shape matches the OpenAI API contract closely enough that an unmodified OpenAI SDK call works against it after swapping three values: API key, base URL, and model name. The minimum surface in practice is POST /v1/chat/completions with messages, model, and an OpenAI-shaped streaming response.

30-second comparison

ProviderMain inference authHeader shapeExtra headers / account contextOAuth or service-account pathProduction gotcha
OpenAIAPI key or short-lived access tokenAuthorization: Bearer <token>Optional organization/project headers for some account setupsWorkload identity federation can create short-lived access tokensLegacy user keys and project keys can resolve billing/context differently; log request IDs for support.
AnthropicAPI keyx-api-key: <key> plus anthropic-versionAdmin API uses Admin API keys for organization resourcesOAuth is not the normal public inference path401 and 403 usually mean malformed/revoked key, missing access, or wrong workspace/org context.
DashScope / Alibaba Model StudioModel Studio API keyOpenAI-compatible calls use SDK api_key; raw HTTP commonly maps to bearer-style authWorkspace-specific domains include {WorkspaceId} in the endpointAlibaba Cloud RAM/account controls sit around key creation and workspace accessKeys are region/workspace sensitive; China, Singapore, Japan, US, and Hong Kong endpoints differ.
DeepSeekAPI keyAuthorization: Bearer ${DEEPSEEK_API_KEY}Separate OpenAI-format and Anthropic-format base URLsNot the primary public inference pathOpenAI-compatible SDKs work once base_url and key are changed.
SiliconFlowAPI keyOpenAPI declares bearerAuthBase URL https://api.siliconflow.com/v1 (or regional variant where used)Not the primary public inference pathModel availability can change; auth may succeed while a model ID fails.
Google GeminiGemini API key for AI Studio / Gemini API; OAuth for Google Cloud APIsAPI key via SDK/env or request key parameter; OAuth bearer for Cloud APIsProject and quota context matter on Google CloudOAuth 2.0, Application Default Credentials, and service accounts are standard Google Cloud pathsChoose the auth path by product surface: AI Studio API key vs Vertex AI / Google Cloud identity.

Why LLM API auth differs so much

The API shape reflects how each company sells and secures model access:

  • Developer-first model APIs usually start with long-lived API keys because they are easy to paste into an SDK.
  • Enterprise cloud platforms add workspace, project, IAM, RAM, or service-account layers because billing, policy, and audit boundaries matter.
  • Admin APIs often require a different credential class than inference APIs because they can list users, keys, audit logs, or organization settings.
  • OpenAI-compatible endpoints normalize request bodies, but they do not fully normalize account identity. You still need the provider's key, endpoint, model ID, and account context.

That last point is the trap: an OpenAI-compatible SDK can hide most client-code differences, but it cannot make an Anthropic key valid on DeepSeek or infer which Alibaba workspace should pay for a request.

Provider-by-provider authentication notes

OpenAI

OpenAI's current API reference accepts bearer credentials from standard API keys or short-lived access tokens created through workload identity federation. HTTP requests use:

Authorization: Bearer OPENAI_API_KEY_OR_ACCESS_TOKEN

OpenAI also separates normal API keys from Admin API keys for organization workflows such as users, projects, API keys, and audit logs. If your account uses multiple organizations or project-scoped access, include the relevant organization/project context where the API or SDK requires it. Treat project keys as the default for new application services and reserve Admin API keys for automation that truly needs administrative scope.

Anthropic

Anthropic's public Claude API commonly uses an API key in the x-api-key header, and calls also include an anthropic-version header. Anthropic's documentation and search results also distinguish Admin API credentials: Admin API keys start with an admin-specific prefix and are sent in x-api-key for organization administration endpoints.

For gateway teams, the operational rule is simple: keep inference keys and admin keys in separate secret stores, separate environment variables, and separate allowlists. Do not let an inference proxy path hold an admin credential just because both are "Anthropic keys."

DashScope / Alibaba Model Studio

Alibaba Model Studio asks you to create a Model Studio API key before using models or applications. The official OpenAI-compatible chat documentation says migration requires changing the API key, BASE_URL, and model name. It also documents workspace-specific domains for regions such as China (Beijing), Singapore, Japan, US (Virginia), and China (Hong Kong).

That means DashScope auth is not just a token string. Your endpoint can encode region and workspace context, and API key permissions can be configured with all-model access or custom restrictions such as IP whitelist and model scope. In production, store the key and base URL together as one provider credential profile.

DeepSeek

DeepSeek documents an OpenAI-compatible base URL (https://api.deepseek.com) and shows raw HTTP calls with:

Authorization: Bearer ${DEEPSEEK_API_KEY}

It also exposes an Anthropic-format base URL for Anthropic-compatible clients. Auth remains provider-specific even when the protocol is compatible: changing only the URL without changing the credential is not enough.

SiliconFlow

SiliconFlow's OpenAPI documentation for chat completions declares bearerAuth and a server URL of https://api.siliconflow.com/v1. In OpenAI-compatible clients, that typically means configuring a SiliconFlow API key and base URL while keeping the familiar chat.completions request body.

Because SiliconFlow aggregates many model families, distinguish authentication success from model authorization or availability. A 200 on a cheap test model does not prove every model ID in your routing table is enabled for that account.

Google Gemini and Google Cloud

Google is the easiest provider to misconfigure because it has multiple valid auth stories. Gemini API quickstarts often use API keys for AI Studio-style access. Google Cloud services, including Vertex AI paths, use Google Cloud authentication patterns: OAuth 2.0, Application Default Credentials, and service accounts.

Use a simple split:

  • For a lightweight Gemini API integration, use the Gemini API key path documented for that API surface.
  • For enterprise workloads on Google Cloud, use service accounts or workload identity via Application Default Credentials and let IAM define what the caller can access.
  • Do not mix API-key and service-account assumptions in the same deployment variable name. Name credentials after the product surface, not just GOOGLE_API_KEY.

Gateway passthrough and credential normalization

An OpenAI-compatible gateway such as TheRouter can help standardize the client-facing API path: your app sends OpenAI-style requests to one base URL, and routing policy selects configured providers/models behind it. That does not mean the gateway should erase provider auth semantics.

A robust gateway credential model keeps four layers separate:

  1. Client-to-gateway authentication — how your application authenticates to the gateway.
  2. Gateway policy identity — which project, team, budget, or route table the request belongs to.
  3. Provider credential profile — provider key, base URL, region, workspace, and optional headers.
  4. Provider response metadata — request IDs, rate-limit headers, auth errors, and billing/account signals.

TheRouter supports OpenAI-compatible routing patterns where configured provider paths exist. Avoid stronger claims: no gateway can truthfully promise support for every model, zero downtime, or the cheapest provider for every request. The value is controlled normalization: fewer SDK branches for the app, with provider-specific credentials still managed explicitly.

Decision tree: key, OAuth, service account, or proxy credential?

  1. Is this a browser/mobile client? Never put provider keys there. Authenticate the user to your backend or gateway, then call providers server-side.
  2. Is this a server calling a developer API? Use provider API keys or short-lived provider tokens if supported. Store them in a secret manager, not source code.
  3. Is this a Google Cloud or enterprise cloud workload? Prefer service accounts, workload identity, or ADC where the provider supports it.
  4. Is this an admin automation? Use admin-scoped credentials only in a separate job or service account with tight access control.
  5. Is this multi-provider routing? Give each provider+region+workspace a named credential profile and route by profile, not by raw key string.

Common 401/403 causes

SymptomLikely causeCheck
401 immediately on every requestMissing, malformed, expired, or revoked credentialPrint only key prefix/length; verify environment variable injection; rotate if exposed.
403 after auth succeedsKey lacks model, project, workspace, or region permissionCheck project/workspace membership and model enablement.
Works locally, fails in CISecret not mounted or named differentlyCompare env var names and CI secret scope.
Works for one model, fails for anotherAccount not authorized for that model or model is unavailableTest a known-enabled model and inspect provider error body.
OpenAI SDK says unauthorized after changing base_urlStill using the old provider keyPair base_url, key, and model in one config object.
Google call fails with confusing quota/project errorAPI key path mixed with Google Cloud project identityConfirm whether the API surface expects Gemini API key or OAuth/ADC.

Implementation pattern: credential profiles

type ProviderCredentialProfile = {
  id: string;
  provider: "openai" | "anthropic" | "dashscope" | "deepseek" | "siliconflow" | "google";
  baseUrl: string;
  auth: {
    type: "bearer" | "x-api-key" | "google-api-key" | "oauth" | "service-account";
    secretRef: string;
  };
  headers?: Record<string, string>;
  workspace?: string;
  project?: string;
  region?: string;
};

Keep this object out of application code. The app should request model: "claude-opus-4.6" or model: "qwen3.7-plus"; routing config should decide which credential profile is attached.

Production checklist

  • Inventory every provider credential by provider, environment, project, workspace, region, owner, and expiry/rotation policy.
  • Separate inference credentials from admin credentials.
  • Store base URL, region/workspace, and auth type with the key.
  • Add a low-cost health check per provider profile and per critical model family.
  • Log provider request IDs and sanitized auth failure categories.
  • Never log full keys, OAuth tokens, service-account JSON, or signed headers.
  • Cross-link auth errors to your runbook and error-handling reference.
  • Route browser and mobile traffic through your backend or gateway; never expose provider keys client-side.

FAQ

Is Authorization: Bearer universal for LLM APIs?

No. It is common among OpenAI-compatible providers such as OpenAI, DeepSeek, and SiliconFlow, but Anthropic's native API uses x-api-key, and Google can use API keys or OAuth depending on the product surface.

Can a gateway hide all provider authentication differences?

It can hide many client-code differences, but it still needs provider-specific credential profiles behind the scenes. Treat normalization as an operational control, not magic compatibility.

Should I use one provider key for every service?

No. Use separate keys per environment, workload, and blast-radius boundary. That makes rotation and incident response much easier.

Are OAuth and service accounts always better than API keys?

Not always. They are better for cloud-native identity, short-lived credentials, and enterprise IAM boundaries. API keys are still the documented path for many developer model APIs.

Sources

Customer Support