Okta Auth JavaScript SDK
repository·master·Indexed 19 days ago
https://github.com/okta/okta-auth-jsA 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.
What's inside @okta/okta-auth-js
- The MyAccount API enables end-user account management within Single Page Applications (SPAs). To use these APIs, you must obtain an access token via OAuth flows that includes the necessary scopes for the specific resource you wish to manage.
Overview of the Okta Authentication API (authn)
masterThe 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.
Introduction to the IDX module
masterThe
IDXmodule 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 olderauthnAPI, theIDXAPI 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.How the centralized transaction (idxStates) handler works
masterBecause 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:
- Inspecting
transaction.statusto determine the current state of the request. - Using
transaction.nextStepto dispatch the request to the appropriate route or logic flow.
This implementation can be found in
web-server/utils/handleTransaction.js.- Inspecting
Use the MyAccount API for end-user account management
masterThe 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:
Resource Read Scopes Manage Scopes Profile okta.myAccount.profile.readokta.myAccount.profile.manageEmail okta.myAccount.email.readokta.myAccount.email.managePhone okta.myAccount.phone.readokta.myAccount.phone.managePassword okta.myAccount.password.readokta.myAccount.password.manageHandle external IDPs in popups with getWithIDPPopup()
masterThe
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
getWithPopupusesokta_post_messagefor communication. However, if an external IDP sets a strictCross-Origin-Opener-Policy(COOP), the popup and main window become isolated, breakingwindow.postMessagecommunication.getWithIDPPopupuses aqueryresponse mode instead, making it resilient to strict COOP policies.Tradeoffs & Requirements:
- No direct communication: The popup cannot talk to the main window via
postMessage. - Manual Redirect Handling: After authentication, the popup must redirect to a registered
redirectUrion your origin. This route must callauthClient.handleIDPPopupRedirect()to relay the OAuth2 response back to the main window. - 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);- No direct communication: The popup cannot talk to the main window via
Step Mode vs Legacy Mode in IDX
masterAs 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.proceedmust include either anactionsorstepproperty 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 callidx.proceedfor each step.Limitations of Step Mode:
- No recursive remediation (automatic calls).
flowis not supported.Up-frontapproach 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 theUp-frontapproach. Use it only as a temporary migration aid.Legacy Mode can be enabled during
OktaAuthconstruction 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 });Understand the OktaAuthMyAccountInterface
masterThe
OktaAuthMyAccountInterfaceis a specialized interface within the@okta/okta-auth-js/myaccountmodule. It extendsOktaAuthOAuthInterface, 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: ExtendsOAuthTransactionMeta(defaults toPKCETransactionMeta).S: ExtendsOAuthStorageManagerInterface<M>(defaults toOAuthStorageManagerInterface<M>).O: ExtendsOktaAuthOAuthOptions(defaults toOktaAuthOAuthOptions).
Key Inherited Properties
token: Access theTokenAPI.session: Access theSessionAPI.pkce: Access thePkceAPI.storageManager: Access theOAuthStorageManagerInterface.transactionManager: Access theTransactionManagerInterface.
How IDX Flows work
masterA 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, theflowfeature is not supported in the default IDX client. Instead of using theflowproperty, you should callidx.proceed({ step: '...' })to drive the client into the desired state. To use the oldflowbehavior, you must enable Legacy Mode.Flow Entrypoints
The
flowis automatically set when calling these methods:idx.authenticate(sets flow todefault)idx.register(sets flow toregister)idx.recoverPassword(sets flow torecoverPassword)idx.unlockAccount(sets flow tounlockAccount)
Managing Flows
You can manually set or retrieve the current flow using:
idx.getFlow(): Returns the currentFlowIdentifier.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' });Configure OAuth 2.0 authentication flows
masterThe SDK supports several flows depending on your client type:
- PKCE OAuth 2.0 flow (Recommended for SPAs): This is the default. It is secure for browser and NodeJS applications. It requires
crypto.subtleandTextEncodersupport. - Authorization Code flow (For Web/Native clients): Use this if you have a client secret stored securely. Set
responseType: 'code'andpkce: false. - Implicit OAuth 2.0 flow (Discouraged): Use only if PKCE cannot be supported. Set
pkce: falseto 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', };- PKCE OAuth 2.0 flow (Recommended for SPAs): This is the default. It is secure for browser and NodeJS applications. It requires
How background services work (autoRenew, syncStorage, etc.)
masterThe
servicesconfiguration manages background tasks that improve user experience and security. These requireOktaAuthto be running as a service.autoRenew: Whentrue, 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.isAuthenticatedis called.
syncStorage: Automatically syncs tokens across browser tabs usingBroadcastChannel,IndexedDB, orlocalStorage. This prevents multiple tabs from sending simultaneous refresh requests.renewOnTabActivation: When enabled (requiresautoRenew: true), the SDK uses the Page Visibility API to attempt a token renewal when a tab becomes active after an inactivity period defined bytabInactivityDuration(default 1800s).
// Example service configuration services: { autoRenew: true, autoRemove: true, syncStorage: true, renewOnTabActivation: true, tabInactivityDuration: 1800 // seconds }Understand IDX Response fields
masterMost IDX methods resolve an
IdxTransactionobject. Understanding these fields is critical for driving the flow.status(IdxStatus)IdxStatus.SUCCESS: Flow ended successfully;tokensare available.IdxStatus.PENDING: Flow in progress; checknextStepto proceed.IdxStatus.FAILURE: SDK-level error; checkerrorfield.IdxStatus.TERMINAL: Flow reached a terminal state; checkmessages.IdxStatus.CANCELED: Flow was canceled (usually viaidx.cancel()).
nextStep(Available inPENDINGstatus)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 onSUCCESS. Contains session tokens.messages: ContainsForm messageorTerminal messagefrom the engine.error: Available onFAILURE.meta: Available onstartTransaction; contains PKCE meta,interactionHandle, etc.enabledFeatures: Available onstartTransaction; lists features allowed by policy.availableSteps: Available onstartTransaction; lists possible next steps.