Skip to content

fix(azure): treat JWT-like api_key as Bearer token for AAD authentication - #3783

Open
dajiaohuang wants to merge 3 commits into
openai:mainfrom
dajiaohuang:fix/3282-azure-aad-token-regression
Open

fix(azure): treat JWT-like api_key as Bearer token for AAD authentication#3783
dajiaohuang wants to merge 3 commits into
openai:mainfrom
dajiaohuang:fix/3282-azure-aad-token-regression

Conversation

@dajiaohuang

Copy link
Copy Markdown

Summary

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.

Root Cause

In v2.34.0, the _auth_headers method was introduced which returns {"api-key": ...} when azure_ad_token is None. This caused AAD tokens passed via api_key to be sent as api-key header instead of Authorization: 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

  • Syntax check passed
  • Manual code review

Related Issue

Fixes #3282

…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
@dajiaohuang
dajiaohuang requested a review from a team as a code owner September 2, 2026 11:23
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 2, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-02T11:30:54.582934Z a4bc984 PR opened
🔒 Security Review Completed 2026-09-02T11:32:02.207608Z a4bc984 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/openai/lib/azure.py
Comment on lines +470 to +471
if _is_jwt(self.api_key):
return {"Authorization": f"Bearer {self.api_key}"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/openai/lib/azure.py
"""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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AzureOpenAI with AAD bearer token passed via api_key works in 2.33.0 but returns 401 in 2.34.0 and after

1 participant