Skip to content

Add support for token provider#8

Closed
deyaaeldeen wants to merge 1 commit into
masterfrom
feat/token-provider
Closed

Add support for token provider#8
deyaaeldeen wants to merge 1 commit into
masterfrom
feat/token-provider

Conversation

@deyaaeldeen
Copy link
Copy Markdown
Owner

@deyaaeldeen deyaaeldeen commented Jul 10, 2025

Add Token Provider Support for Dynamic Authentication

Overview

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.

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 5 times, most recently from c97adeb to 9c6db75 Compare July 12, 2025 22:39
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.

1 participant