Generic OAuth2 token manager supporting multiple grant types and automatic token refresh.

This class provides a standardized way to handle OAuth2 authentication flows including:

  • Authorization code flow (with PKCE support)
  • Client credentials flow
  • Refresh token flow
  • Direct access token usage

Features:

  • Automatic token refresh before expiration
  • Thread-safe token refresh (prevents concurrent refresh requests)
  • Provider customization hooks for non-standard OAuth2 implementations
  • Token persistence callbacks
  • Support for multiple grant types

Example

// Initialize with client credentials
const oauth = new OAuth2Manager({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
tokenEndpoint: 'https://api.example.com/oauth/token',
authorizationEndpoint: 'https://api.example.com/oauth/authorize',
scopes: ['read', 'write']
});

// Get a valid access token (auto-refreshes if needed)
const token = await oauth.getAccessToken();

// Use the token in API requests
const response = await fetch('https://api.example.com/data', {
headers: { 'Authorization': `Bearer ${token}` }
});

Constructors

Properties

accessToken: string = null
config: Required<Omit<OAuth2Config, "authorizationEndpoint" | "redirectUri" | "scopes" | "accessToken" | "refreshToken" | "tokenExpiresAt" | "tokenResponseTransform" | "tokenRequestTransform" | "additionalHeaders" | "onTokenUpdate">> & Pick<OAuth2Config, "authorizationEndpoint" | "redirectUri" | "scopes" | "tokenResponseTransform" | "tokenRequestTransform" | "additionalHeaders" | "onTokenUpdate">
refreshPromise: Promise<string> = null
refreshToken: string = null
tokenExpiresAt: number = 0

Methods

  • Gets a valid access token, automatically refreshing if needed

    This is the main method to use when you need an access token for API requests. It handles token refresh automatically if the current token is expired or about to expire.

    Returns Promise<string>

    A valid access token

    Throws

    Error if no token is available and cannot be obtained

  • Gets the authorization URL for the authorization code flow

    Parameters

    • Optional state: string

      Optional state parameter for CSRF protection

    • Optional additionalParams: Record<string, string>

      Additional query parameters to include

    Returns string

    The authorization URL

  • Sets the access token directly (for cases where token is obtained externally)

    Parameters

    • accessToken: string

      The access token

    • Optional refreshToken: string

      Optional refresh token

    • Optional expiresIn: number

      Optional expiration time in seconds

    Returns void