Okta Auth JavaScript SDK

repository·master·Indexed 19 days ago

https://github.com/okta/okta-auth-js

A client-side library built on Okta's Authentication and OpenID Connect & OAuth 2.0 APIs, enabling developers to create custom, branded sign-in experiences. The SDK includes a MyAccount submodule for end-user account management of profiles, emails, phones, and passwords in Single Page Applications (SPAs). It supports installation via NPM, Yarn, or CDN, and provides TypeScript definitions and polyfills for legacy browser compatibility.

Tokens
44.4K
Snippets
144
Records
201
Agent score
65%

What's inside @okta/okta-auth-js

  1. Overview of the Okta Authentication API (authn)

    master

    The Okta Authentication API (authn) provides core identity operations, including:

    • User authentication
    • Multi-factor authentication (MFA) enrollment and verification
    • Password recovery
    • Account unlocking

    It can be used as a standalone identity layer for your application or integrated with the Okta Sessions API to obtain an Okta session cookie for accessing apps within Okta.

  2. Introduction to the IDX module

    master

    The IDX module is designed to communicate with Okta as an OAuth 2.0 + OpenID Connect provider. It is specifically built to work with [Okta's Identity Engine][] to facilitate user authentication and registration. Unlike the older authn API, the IDX API enables advanced features like multi-factor authentication (MFA) without requiring a redirect to Okta.

    Note: Using this module requires access to the Okta Identity Engine. If you do not have access, contact your account manager or reach out to oie@okta.com.

  3. How the centralized transaction (idxStates) handler works

    master

    Because the Okta Identity Engine operates as a state machine, it returns different states in response to requests. To manage these complex states, this sample implements a centralized transaction handler pattern.

    This pattern works by:

    1. Inspecting transaction.status to determine the current state of the request.
    2. Using transaction.nextStep to dispatch the request to the appropriate route or logic flow.

    This implementation can be found in web-server/utils/handleTransaction.js.

  4. Use the MyAccount API for end-user account management

    master

    The MyAccount API allows Single Page Applications (SPAs) to perform end-user account management tasks. To use these APIs, you must obtain an access token via OAuth flows using specific scopes.

    Required Scopes

    Permissions are granular based on the resource being accessed:

    ResourceRead ScopesManage Scopes
    Profileokta.myAccount.profile.readokta.myAccount.profile.manage
    Emailokta.myAccount.email.readokta.myAccount.email.manage
    Phoneokta.myAccount.phone.readokta.myAccount.phone.manage
    Passwordokta.myAccount.password.readokta.myAccount.password.manage
  5. Handle external IDPs in popups with getWithIDPPopup()

    master

    The token.getWithIDPPopup(options) method (web browser only, async) is a specialized version of the popup flow designed for deployments using External Identity Providers.

    Why use this? Standard getWithPopup uses okta_post_message for communication. However, if an external IDP sets a strict Cross-Origin-Opener-Policy (COOP), the popup and main window become isolated, breaking window.postMessage communication. getWithIDPPopup uses a query response mode instead, making it resilient to strict COOP policies.

    Tradeoffs & Requirements:

    1. No direct communication: The popup cannot talk to the main window via postMessage.
    2. Manual Redirect Handling: After authentication, the popup must redirect to a registered redirectUri on your origin. This route must call authClient.handleIDPPopupRedirect() to relay the OAuth2 response back to the main window.
    3. User Experience: The flow may feel less seamless than a standard popup due to the redirect requirement.
    const { promise, cancel } = authClient.token.getWithIDPPopup({
      redirectUri: 'http://localhost:8080/popup/callback',
    });
    const { tokens } = await promise;
    authClient.tokenManager.setTokens(tokens);
  6. Step Mode vs Legacy Mode in IDX

    master

    As of auth-js@8.x, the IDX client uses Step Mode by default. This mode requires explicit remediation steps, making client behavior consistent but requiring more code to manage the flow.

    Step Mode (Default)

    In Step Mode, every call to idx.proceed must include either an actions or step property to name the remediation to run. The client will execute that specific remediation and return the response, but it will not automatically perform subsequent (recursive) remediations. You must manually call idx.proceed for each step.

    Limitations of Step Mode:

    • No recursive remediation (automatic calls).
    • flow is not supported.
    • Up-front approach is not supported.

    Legacy Mode (Deprecated)

    Legacy Mode preserves pre-8.x behavior and is on a deprecation path. It supports recursive remediation, flow, and the Up-front approach. Use it only as a temporary migration aid.

    Legacy Mode can be enabled during OktaAuth construction or on a per-call basis.

    // Enable Legacy Mode globally during construction
    const oktaAuth = new OktaAuth({
      ...config,
      idx: { enableLegacyMode: true }
    });
    
    // OR enable Legacy Mode for a specific call
    const response = await idx.proceed({
      username: 'foo@bar.com',
      enableLegacyMode: true
    });
  7. Understand the OktaAuthMyAccountInterface

    master

    The OktaAuthMyAccountInterface is a specialized interface within the @okta/okta-auth-js/myaccount module. It extends OktaAuthOAuthInterface, meaning it inherits all standard OAuth and OIDC capabilities (like token management, session handling, and sign-in/out) while providing additional properties and methods specific to 'My Account' functionality.

    Type Parameters

    • M: Extends OAuthTransactionMeta (defaults to PKCETransactionMeta).
    • S: Extends OAuthStorageManagerInterface<M> (defaults to OAuthStorageManagerInterface<M>).
    • O: Extends OktaAuthOAuthOptions (defaults to OktaAuthOAuthOptions).

    Key Inherited Properties

    • token: Access the TokenAPI.
    • session: Access the SessionAPI.
    • pkce: Access the PkceAPI.
    • storageManager: Access the OAuthStorageManagerInterface.
    • transactionManager: Access the TransactionManagerInterface.
  8. How IDX Flows work

    master

    A flow is a sequence of remediations used to bootstrap an IDX transaction to a specific user experience (e.g., unlock-account, register, recoverPassword).

    Note: As of auth-js@8.x, the flow feature is not supported in the default IDX client. Instead of using the flow property, you should call idx.proceed({ step: '...' }) to drive the client into the desired state. To use the old flow behavior, you must enable Legacy Mode.

    Flow Entrypoints

    The flow is automatically set when calling these methods:

    • idx.authenticate (sets flow to default)
    • idx.register (sets flow to register)
    • idx.recoverPassword (sets flow to recoverPassword)
    • idx.unlockAccount (sets flow to unlockAccount)

    Managing Flows

    You can manually set or retrieve the current flow using:

    • idx.getFlow(): Returns the current FlowIdentifier.
    • idx.setFlow(flow): Manually sets the flow.
    • idx.startTransaction({ flow: '...' }): Starts a transaction with a specific flow identifier.
    // Starting a flow via entrypoint
    await authClient.idx.recoverPassword();
    const flow = authClient.idx.getFlow(); // "recoverPassword"
    
    // Starting a flow via startTransaction
    await authClient.idx.startTransaction({ flow: 'recoverPassword' });
  9. Configure OAuth 2.0 authentication flows

    master

    The SDK supports several flows depending on your client type:

    1. PKCE OAuth 2.0 flow (Recommended for SPAs): This is the default. It is secure for browser and NodeJS applications. It requires crypto.subtle and TextEncoder support.
    2. Authorization Code flow (For Web/Native clients): Use this if you have a client secret stored securely. Set responseType: 'code' and pkce: false.
    3. Implicit OAuth 2.0 flow (Discouraged): Use only if PKCE cannot be supported. Set pkce: false to enable. This is less secure as raw tokens are exposed in browser history.
    // Example: Authorization Code flow
    var config = {
      issuer: 'https://{yourOktaDomain}/oauth2/default',
      clientId: 'GHtf9iJdr60A9IYrR0jw',
      redirectUri: 'https://acme.com/oauth2/callback/home',
      responseType: 'code',
      pkce: false
    };
    
    // Example: Implicit flow
    var config = {
      pkce: false,
      issuer: 'https://{yourOktaDomain}/oauth2/default',
    };
  10. How background services work (autoRenew, syncStorage, etc.)

    master

    The services configuration manages background tasks that improve user experience and security. These require OktaAuth to be running as a service.

    • autoRenew: When true, the library attempts to renew tokens before they expire.
      • Active strategy: Background network requests refresh tokens seamlessly.
      • Passive strategy: Refresh attempts only occur when oktaAuth.isAuthenticated is called.
    • syncStorage: Automatically syncs tokens across browser tabs using BroadcastChannel, IndexedDB, or localStorage. This prevents multiple tabs from sending simultaneous refresh requests.
    • renewOnTabActivation: When enabled (requires autoRenew: true), the SDK uses the Page Visibility API to attempt a token renewal when a tab becomes active after an inactivity period defined by tabInactivityDuration (default 1800s).
    // Example service configuration
    services: {
      autoRenew: true,
      autoRemove: true,
      syncStorage: true,
      renewOnTabActivation: true,
      tabInactivityDuration: 1800 // seconds
    }
  11. Understand IDX Response fields

    master

    Most IDX methods resolve an IdxTransaction object. Understanding these fields is critical for driving the flow.

    status (IdxStatus)

    • IdxStatus.SUCCESS: Flow ended successfully; tokens are available.
    • IdxStatus.PENDING: Flow in progress; check nextStep to proceed.
    • IdxStatus.FAILURE: SDK-level error; check error field.
    • IdxStatus.TERMINAL: Flow reached a terminal state; check messages.
    • IdxStatus.CANCELED: Flow was canceled (usually via idx.cancel()).

    nextStep (Available in PENDING status)

    Contains instructions for the next interaction:

    • name: Identifier of the next step.
    • type: Type of the authenticator.
    • authenticator: The authenticator object.
    • canSkip: Boolean indicating if the step is skippable.
    • inputs: Array of required parameters (e.g., [{ name: 'username', label: 'Username' }]).
    • poll: Polling configuration (if applicable).

    Other Fields

    • tokens: Available on SUCCESS. Contains session tokens.
    • messages: Contains Form message or Terminal message from the engine.
    • error: Available on FAILURE.
    • meta: Available on startTransaction; contains PKCE meta, interactionHandle, etc.
    • enabledFeatures: Available on startTransaction; lists features allowed by policy.
    • availableSteps: Available on startTransaction; lists possible next steps.