Skip to content

add support for token provider #1587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

deyaaeldeen
Copy link
Contributor

  • I understand that this repository is auto-generated and my pull request may not be merged

Changes being requested

This PR introduces a new tokenProvider option to the OpenAI client, enabling dynamic token retrieval for authentication scenarios where API keys need to be refreshed or obtained at runtime.

Additional context & links

Changes

New Feature: tokenProvider Option

  • Added TokenProvider type definition: () => Promise<AccessToken>
  • Added AccessToken interface with token: string property
  • Added tokenProvider option to ClientOptions interface
  • Implemented token provider logic in the _setToken() method

Key Benefits

  1. Dynamic Authentication: Supports scenarios where tokens expire and need to be refreshed
  2. Enhanced Security: Tokens can be retrieved just-in-time rather than stored statically
  3. Enterprise Integration: Enables integration with corporate identity providers and token management systems
  4. Flexible Authentication: Provides an alternative to static API keys for environments requiring dynamic credentials

Implementation Details

Client Construction:

  • tokenProvider and apiKey are mutually exclusive - only one can be provided
  • If neither is provided, an error is thrown requiring one of the two authentication methods
  • Browser usage automatically allowed when using tokenProvider (sets dangerouslyAllowBrowser: true)

Token Management:

  • _setToken() method now returns a boolean indicating if a token was successfully retrieved
  • Token provider is called on every request preparation via prepareOptions()

Usage Example

const client = new OpenAI({
  tokenProvider: async () => {
    // Fetch token from your auth service
    const response = await fetch('/api/auth/token');
    const data = await response.json();
    return { token: data.access_token };
  }
});

Backward Compatibility

This change is fully backward compatible. Existing code using apiKey continues to work unchanged. The new tokenProvider option is purely additive.


@deyaaeldeen deyaaeldeen force-pushed the feat/token-provider branch from 276b556 to b4dd476 Compare July 16, 2025 23:36
@deyaaeldeen deyaaeldeen force-pushed the feat/token-provider branch from b4dd476 to f514473 Compare July 16, 2025 23:40
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.

2 participants