fix(azure): treat JWT-like api_key as Bearer token for AAD authentication - #3783
fix(azure): treat JWT-like api_key as Bearer token for AAD authentication#3783dajiaohuang wants to merge 3 commits into
Conversation
…nnotation Replace construct_type call with explicit str coercion to properly handle numeric code values returned by the API. Fixes openai#3781
Validate expires_in to reject negative values, zero, NaN, infinity, and overflow values (e.g. 10**400). Convert bool to int first since bool is a subclass of int. Fixes openai#3735
…tion When users pass an Azure AD access token (which is a JWT) as the api_key parameter, the SDK now detects this and sends it as an Authorization: Bearer header instead of api-key header. This fixes issue openai#3282 where AAD tokens passed via api_key started returning 401 in v2.34.0+ because they were being sent as api-key instead of Bearer. The detection is based on the JWT format: tokens starting with "eyJ" followed by two dots are treated as JWT/AAD tokens. Fixes: openai#3282
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a4bc984c93
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _is_jwt(self.api_key): | ||
| return {"Authorization": f"Bearer {self.api_key}"} |
There was a problem hiding this comment.
Stop re-adding JWTs as API keys
When a JWT-like value is supplied through api_key, _prepare_options() still inserts it into the api-key header before _build_headers() merges in this new Bearer header. Consequently, both synchronous and asynchronous HTTP requests send both authentication headers rather than replacing API-key authentication, so Azure deployments that reject or prioritize the invalid API-key credential can still return 401. Handle _is_jwt() in both _prepare_options() implementations and add sync/async assertions against the final request headers.
AGENTS.md reference: AGENTS.md:L41-L45
Useful? React with 👍 / 👎.
| """Check if a token looks like a JWT (used for Azure AD tokens).""" | ||
| # JWT tokens have three parts separated by dots: header.payload.signature | ||
| # The header is base64-encoded and typically starts with "eyJ" for RS256/HS256 tokens | ||
| return token.startswith("eyJ") and token.count(".") == 2 |
There was a problem hiding this comment.
Apply JWT detection to Realtime authentication
For Realtime connections using a JWT-like api_key, both _configure_realtime() implementations bypass this helper and unconditionally emit api-key, so the advertised AAD-token compatibility still fails during WebSocket authentication even though ordinary requests attempt Bearer authentication. Apply the same detection when constructing sync and async Realtime headers and cover both entry points.
AGENTS.md reference: AGENTS.md:L41-L45
Useful? React with 👍 / 👎.
| if isinstance(expires_in, bool): | ||
| expires_in = int(expires_in) | ||
| if not isinstance(expires_in, (int, float)) or math.isnan(expires_in) or math.isinf(expires_in) or expires_in <= 0: | ||
| raise ValueError("Token exchange response did not include a valid expires_in") |
There was a problem hiding this comment.
Preserve OpenAIError for invalid expirations
When a subject-token exchange returns a missing, nonnumeric, nonpositive, or nonfinite expires_in, this changes the established failure from OpenAIError to ValueError, unlike the other malformed token-response fields handled immediately above. Applications catching SDK authentication errors can therefore unexpectedly receive an uncaught built-in exception; retain OpenAIError while performing the stricter validation and cover synchronous and asynchronous exchange paths.
AGENTS.md reference: AGENTS.md:L41-L45
Useful? React with 👍 / 👎.
Summary
When users pass an Azure AD access token (which is a JWT) as the
api_keyparameter, the SDK now detects this and sends it as anAuthorization: Bearerheader instead ofapi-keyheader.Root Cause
In v2.34.0, the
_auth_headersmethod was introduced which returns{"api-key": ...}whenazure_ad_tokenis None. This caused AAD tokens passed viaapi_keyto be sent asapi-keyheader instead ofAuthorization: Bearer, resulting in 401 errors.Fix
Added JWT detection in
_auth_headers- tokens that start with "eyJ" and contain two dots (standard JWT format) are treated as Azure AD tokens and sent as Bearer tokens.Testing
Related Issue
Fixes #3282