Client configuration and authentication
Purpose and Scope
This page explains how authentication information reaches OpenAI API requests in the TypeScript and JavaScript SDK, and how that relates to per-request configuration. For most applications, configuration begins with constructing an OpenAI client using an API key, usually sourced from the environment. From there, generated resource methods handle bearer authentication, merge request options, and add feature-specific beta headers where required. More advanced deployments can avoid long-lived API keys by using workload identity federation, where an external platform identity is exchanged for an OpenAI access token before requests are sent. Sources: README.md, src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts
The repository exposes two complementary authentication layers. The normal SDK layer sends OpenAI API requests through generated resource methods, while the workload identity layer obtains a token from a cloud or Kubernetes identity provider and exchanges it with OpenAI authentication infrastructure. Generated resources such as ChatKit sessions and Realtime sessions show the request-level contract: methods accept a body plus optional request options, then call the internal client with a path, merged headers, and bearer authentication metadata. That pattern is the main source-to-code bridge for understanding request overrides. Sources: src/auth/types.ts, src/auth/workload-identity-auth.ts, src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts
Relevant Source Files
- src/auth/types.ts — Defines the public workload identity configuration types, subject token provider contract, token exchange response shape, and refresh buffer option.
- src/auth/index.ts — Re-exports workload identity types, built-in subject token providers, and authentication-related error classes from the auth package surface.
- src/auth/subject-token-providers.ts — Implements built-in Kubernetes, Azure managed identity, and Google Cloud subject token providers used before OpenAI token exchange.
- src/auth/workload-identity-auth.ts — Implements token exchange, access-token caching, refresh coordination, error conversion, and explicit invalidation for workload identity authentication.
- src/resources/beta/chatkit/sessions.ts — Shows a generated bearer-auth resource method that merges request options and beta headers while creating or cancelling ChatKit sessions.
- src/resources/beta/realtime/sessions.ts — Shows a generated bearer-auth resource method that creates Realtime client secrets for browser-side Realtime API authentication.
Core Primitives
The basic primitive is the OpenAI client, which the README demonstrates by importing the default SDK export and passing an API key. The example notes that reading from the standard environment variable is the default behavior, so many server-side applications only need to instantiate the client once and reuse it across requests. After construction, model and platform APIs are reached through resource namespaces such as responses, chat completions, beta ChatKit, and beta Realtime. The generated resource methods decide which HTTP path, body, security requirement, and headers apply to each operation. Sources: README.md, src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts
Request-level configuration is represented by the optional options parameter accepted by generated methods. In the ChatKit sessions resource, create and cancel both accept request options, merge caller-provided headers with an OpenAI beta header, and mark the request with bearer authentication. The Realtime sessions resource follows the same pattern for creating an ephemeral client secret. This matters for organization, project, tracing, idempotency, or experiment headers: when a deployment needs a request-specific header, the generated resource can merge it with required SDK headers rather than replacing them. Sources: src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts
A subject token provider is the workload identity primitive that represents an external identity source. Its contract is intentionally small: it declares whether it returns a JWT or ID token and exposes an asynchronous token getter. A workload identity configuration then binds that provider to an OpenAI identity provider identifier and service account identifier, with optional client identifier and refresh buffer. This separation lets platform-specific token acquisition remain outside the token exchange logic, while the shared authentication class can treat Kubernetes, Azure, Google Cloud, or custom providers uniformly. Sources: src/auth/types.ts, src/auth/index.ts, src/auth/subject-token-providers.ts, src/auth/workload-identity-auth.ts
Authentication Models
API key authentication is the direct model for server-side SDK use. The application constructs the client with a secret key, and generated methods send bearer-authenticated requests to OpenAI endpoints. This model is simple, predictable, and appropriate when the server owns the OpenAI credential. It is different from GPT Action authentication, where an action exposed to ChatGPT may use no authentication, an API key configured in the GPT editor, or OAuth for per-user authorization. Those action choices protect the action provider's API; the SDK client configuration described here protects calls from your code to OpenAI.
Workload identity authentication is intended for automated environments where a platform identity can be verified without distributing a static OpenAI API key. The built-in Kubernetes provider reads and trims a service account token file, the Azure provider calls the instance metadata service with managed identity selectors, and the exported types allow custom providers with the same subject-token contract. Once the subject token is available, the OpenAI workload identity class exchanges it for an access token using the configured identity provider and service account identifiers. Sources: src/auth/types.ts, src/auth/subject-token-providers.ts, src/auth/workload-identity-auth.ts
Execution Flow
The workload identity flow starts when a request path needs a bearer token and the authentication layer calls the token getter. If no cached token exists, or the cached token has expired, the class asks the configured subject token provider for a fresh external token. It then posts a token exchange request containing the token exchange grant type, subject token, subject token type, identity provider identifier, service account identifier, and optional client identifier. A successful response must contain a non-empty access token, and the implementation stores an expiration timestamp for later reuse. Sources: src/auth/workload-identity-auth.ts, src/auth/types.ts
Refresh behavior is designed to avoid unnecessary token exchanges while keeping long-running services healthy. If a token is expired, callers share the same in-flight refresh promise rather than launching duplicate exchanges. If the token is still usable but inside the refresh buffer, the current token can be returned while a background refresh promise is started. The default refresh buffer comes from the workload identity type comments and is twenty minutes, unless the configuration overrides it. This behavior is especially useful for servers with many concurrent requests. Sources: src/auth/types.ts, src/auth/workload-identity-auth.ts
Generated API resources show the final request shape after authentication has been selected. ChatKit session creation posts to the ChatKit sessions endpoint with a user, workflow, optional runtime configuration, expiration override, and optional rate limits, then returns a chat session. Realtime session creation posts session configuration and returns a session object plus a client secret that browser clients can use with the Realtime API. Both operations are authenticated by the server-side client, but the resulting secrets are narrower client-facing credentials for embedded or realtime experiences. Sources: src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts
Compact Reference
| Component | Public shape | Configuration role |
|---|---|---|
| OpenAI client | default SDK client shown in README | Holds the primary API key and base request configuration for normal OpenAI API calls. |
| RequestOptions | optional method argument in generated resources | Allows per-call overrides such as headers while preserving required generated headers. |
| SubjectTokenProvider | token type plus asynchronous token getter | Supplies a Kubernetes, Azure, Google Cloud, or custom external identity token. |
| WorkloadIdentity | identity provider, service account, provider, optional client identifier, refresh buffer | Describes how an external identity maps to an OpenAI service account. |
| WorkloadIdentityAuth | token exchange and cache manager | Exchanges subject tokens for OpenAI access tokens and coordinates refreshes. |
| ChatKit sessions | create and cancel methods | Creates or cancels server-authorized ChatKit sessions with beta headers and bearer auth. |
| Realtime sessions | create method | Creates ephemeral client secrets for browser Realtime API clients. |
Implementation Details and Edge Cases
The subject token providers surface operational failures as authentication-specific errors. The Kubernetes provider catches file-reading failures, preserves existing subject-token errors, wraps unexpected read failures with provider context, trims whitespace, and rejects empty token files. The Azure provider builds a metadata-service URL with resource, API version, and optional object, client, or managed-service-identity resource identifiers. It also supports a custom fetch implementation and timeout, then verifies the HTTP response and JSON access token field before returning the token. Sources: src/auth/subject-token-providers.ts, src/auth/index.ts
Token exchange failures are deliberately separated by status and response shape. When the OpenAI token exchange endpoint returns authentication or authorization failures, the implementation raises an OAuth error for statuses associated with invalid client or subject identity state. Other non-success responses are converted through the SDK API error generator with the response status, parsed body when available, and response headers. Even a successful HTTP response is validated structurally: if the JSON body lacks a usable access token, the code raises an OpenAI error rather than caching an invalid credential. Sources: src/auth/workload-identity-auth.ts, src/auth/types.ts
Practical Configuration Pattern
A typical production service should keep one server-side client near the boundary where outgoing OpenAI requests are made, pass request options only when a particular call needs overrides, and use workload identity only when the environment can provide a trusted external identity. For ChatKit and Realtime browser integrations, the server should create sessions or client secrets using its authenticated SDK client, then hand only the scoped client credential to the frontend. That division keeps long-lived OpenAI credentials on the server while still enabling interactive client-side experiences. Sources: src/resources/beta/chatkit/sessions.ts, src/resources/beta/realtime/sessions.ts, src/auth/workload-identity-auth.ts
Next, read the runtime page if you need custom fetch behavior across Node, Deno, Bun, browsers, or edge environments. Read the workload identity page for provider-specific setup, and read the ChatKit or Realtime pages before issuing client secrets to frontend applications. If you are configuring integrations exposed through ChatGPT Actions or remote MCP servers, treat their user-facing authentication choices as a separate layer from the SDK's OpenAI client authentication.