### start() Source: https://github.com/okta/okta-auth-js/blob/master/README.md Starts the OktaAuth service. This is an asynchronous operation. ```APIDOC ## start() ### Description Starts the `OktaAuth` service. ### Method async ### Endpoint N/A (SDK method) ``` -------------------------------- ### Start App Server and Open Browser Source: https://github.com/okta/okta-auth-js/blob/master/samples/test/README.md Command to start the application server and automatically open a new browser window for testing. Useful for interactive debugging or manual testing. ```bash yarn start:app ``` -------------------------------- ### idx.start Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Starts a new IDX flow. ```APIDOC ## idx.start ### Description Starts a new IDX flow. ### Method APIDOC ### Endpoint APIDOC ### Parameters APIDOC ### Request Example APIDOC ### Response APIDOC ``` -------------------------------- ### Start Webpack Bundle Analyzer Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/tree-shaking/README.md Run this command to start the webpack bundle analyzer in watch mode. This tool helps visualize the bundle contents. ```bash yarn workspace @okta/tree-shaking start ``` -------------------------------- ### Run E2E Tests Source: https://github.com/okta/okta-auth-js/blob/master/test/e2e/README.md Command to start the application server and test runner, executing all specs. Assumes you are in the workspace directory. ```bash yarn workspace @okta/test.e2e start ``` -------------------------------- ### Start E2E Test Runner Source: https://github.com/okta/okta-auth-js/blob/master/samples/test/README.md Command to start the application server and the test runner, executing all defined specs. This is the primary command for running the full suite of E2E tests. ```bash yarn workspace @okta/test.e2e.samples start ``` -------------------------------- ### MFA Enroll Activate Example Response Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md An example of the response object when a factor is in the MFA_ENROLL_ACTIVATE state, including available actions. ```javascript { status: 'MFA_ENROLL_ACTIVATE', expiresAt: '2014-11-02T23:39:03.319Z', factorResult: 'WAITING', // or 'TIMEOUT', user: { id: '00ugti3kwafWJBRIY0g3', profile: { login: 'isaac@example.org', firstName: 'Isaac', lastName: 'Brock', locale: 'en_US', timeZone: 'America/Los_Angeles' }, }, factor: { id: 'opfh52xcuft3J4uZc0g3', provider: 'OKTA', factorType: 'push', profile: {}, activation: { expiresAt: '2015-04-01T15:57:32.000Z', qrcode: { href: 'https://acme.okta.com/api/v1/users/00ugti3kwafWJBRIY0g3/factors/opfh52xcuft3J4uZc0g3/qr/00fukNElRS_Tz6k-CFhg3pH4KO2dj2guhmaapXWbc4', type: 'image/png' } } }, resend: function() { /* returns another transaction */ }, activate: function(options) { /* returns another transaction */ }, poll: function() { /* returns another transaction */ }, prev: function() { /* returns another transaction */ }, cancel: function() { /* terminates the auth flow */ }, data: { /* the parsed json response */ } } ``` -------------------------------- ### Example Authentication Success Response Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md This is an example of a successful authentication response, containing details like expiration time, status, session token, and user profile information. ```json { expiresAt: '2015-06-08T23:34:34.000Z', status: 'SUCCESS', sessionToken: '00p8RhRDCh_8NxIin-wtF5M6ofFtRhfKWGBAbd2WmE', user: { id: '00uhm5QzwyZZxjrfp0g3', profile: { login: 'exampleUser@example.com', firstName: 'Test', lastName: 'User', locale: 'en_US', timeZone: 'America/Los_Angeles' } } } ``` -------------------------------- ### Start Recover Password Flow Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Demonstrates starting a 'recoverPassword' flow by calling the dedicated entrypoint or by passing the flow identifier to `startTransaction`. The 'flow' is automatically set, enabling `proceed` to handle remediations correctly. Starting a new flow discards any existing transaction of a different type. ```javascript // a recover password flow can be started by calling the `recoverPassword` entrypoint await authClient.idx.recoverPassword(); const flow = authClient.idx.getFlow(); // "recoverPassword" // or by passing the flow identifier to `startTransaction` await authClient.idx.startTransaction({ flow: 'recoverPassword' }) ``` -------------------------------- ### Install Okta Auth JS with Yarn or npm Source: https://github.com/okta/okta-auth-js/blob/master/README.md Use these commands to add the Okta Auth JS library to your project dependencies. ```bash # Run this command in your project root folder. # yarn yarn add @okta/okta-auth-js # npm npm install --save @okta/okta-auth-js ``` -------------------------------- ### Clone and Build Okta Auth JS SDK Source: https://github.com/okta/okta-auth-js/blob/master/README.md Clone the repository, navigate into the directory, and install dependencies to build the SDK. The SDK will be built under the `build` folder. ```bash git clone https://github.com/okta/okta-auth-js.git cd okta-auth-js yarn install ``` -------------------------------- ### Generate Specific Sample Source: https://github.com/okta/okta-auth-js/blob/master/samples/README.md Generate a single, specific sample application by providing its name. For example, 'yarn build webpack-spa' generates the 'webpack-spa' sample. ```bash yarn build webpack-spa ``` -------------------------------- ### Authenticate with User Input Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md This example demonstrates how to retrieve required inputs for the next authentication step and then use those inputs to continue the authentication flow. This is part of the On-Demand approach. ```javascript // get "inputs" from the response // inputs: [{ name: 'username', label: 'Username' }] const { nextStep: { inputs } } = await authClient.idx.authenticate(); // gather user inputs (this call should happen in a separated request) const transaction = await authClient.idx.authenticate({ username: 'from user input' }); ``` -------------------------------- ### Start Test Runner Only Source: https://github.com/okta/okta-auth-js/blob/master/samples/test/README.md Command to start only the test runner, executing all defined specs without starting the application server. Use this if the application server is already running. ```bash yarn start:runner ``` -------------------------------- ### Example Commit Message for Specific Package Source: https://github.com/okta/okta-auth-js/blob/master/CONTRIBUTING.md This example demonstrates a commit message for a bug fix in a specific package, 'auth-js'. It follows the template for package-specific changes. ```text fix: Fixes bad bug Fixes a very bad bug in auth-js Resolves: #5678 ``` -------------------------------- ### Example Commit Message Source: https://github.com/okta/okta-auth-js/blob/master/CONTRIBUTING.md An example of a documentation update commit following the standard template. It includes a type, short description, detailed description, and a resolved issue number. ```text docs: Updates CONTRIBUTING.md Updates Contributing.md with new emoji categories Updates Contributing.md with new template Resolves: #1234 ``` -------------------------------- ### MFA_REQUIRED Response Example Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md This is an example of a response when a user is required to provide additional verification with a previously enrolled factor. ```javascript { status: 'MFA_REQUIRED', expiresAt: '2014-11-02T23:39:03.319Z', user: { id: '00ugti3kwafWJBRIY0g3', profile: { login: 'isaac@example.org', firstName: 'Isaac', lastName: 'Brock', locale: 'en_US', timeZone: 'America/Los_Angeles' }, }, factors: [{ id: 'ufsigasO4dVUPM5O40g3', provider: 'OKTA', factorType: 'question', profile: { question: 'disliked_food', questionText: 'What is the food you least liked as a child?' }, verify: function(options) { /* returns another transaction */ } }, { id: 'opfhw7v2OnxKpftO40g3', provider: 'OKTA', factorType: 'push', profile: { credentialId: 'isaac@example.org', deviceType: 'SmartPhone_IPhone', keys: [ { kty: 'PKIX', use: 'sig', kid: 'default', x5c: [ 'MIIBIjANBgkqhkiG9w0BAQEFBAOCAQ8AMIIBCgKCAQEAs4LfXaaQW6uIpkjoiKn2g9B6nNQDraLyC3XgHP5cvX/qaqry43SwyqjbQtwRkScosDHl59r0DX1V/3xBtBYwdo8rAdX3I5h6z8lW12xGjOkmb20TuAiy8wSmzchdm52kWodUb7OkMk6CgRJRSDVbC97eNcfKk0wmpxnCJWhC+AiSzRVmgkpgp8NanuMcpI/X+W5qeqWO0w3DGzv43FkrYtfSkvpDdO4EvDL8bWX1Ad7mBoNVLWErcNf/uI+r/jFpKHgjvx3iqs2Q7vcfY706Py1m91vT0vs4SWXwzVV6pAVjD/kumL+nXfzfzAHw+A2vb6J2w06Rj71bqUkC2b8TpQIDAQAB' ] } ], name: 'Isaac\'s iPhone', platform: 'IOS', version: '8.1.3' }, verify: function() { /* returns another transaction */ } }, { id: 'smsigwDlH85L9FyQK0g3', provider: 'OKTA', factorType: 'sms', profile: { phoneNumber: '+1 XXX-XXX-3355' }, verify: function() { /* returns another transaction */ } }, { id: 'ostigevBq2NObXmTh0g3', provider: 'OKTA', factorType: 'token:software:totp', profile: { credentialId: 'isaac@example.org' }, verify: function() { /* returns another transaction */ } }, { id: 'uftigiEmYTPOmvqTS0g3', provider: 'GOOGLE', factorType: 'token:software:totp', profile: { credentialId: 'isaac@example.org' }, verify: function() { /* returns another transaction */ } }], cancel: function() { /* terminates the auth flow */ }, data: { /* the parsed json response */ } } ``` -------------------------------- ### MFA_CHALLENGE Response Example Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md This is an example of a response when a user must verify a factor-specific challenge. The 'factorResult' indicates the current state of the challenge. ```javascript { status: 'MFA_CHALLENGE', expiresAt: '2014-11-02T23:39:03.319Z', factorResult: 'WAITING', // or CANCELLED, TIMEOUT, or ERROR user: { id: '00ugti3kwafWJBRIY0g3', profile: { login: 'isaac@example.org', firstName: 'Isaac', lastName: 'Brock', locale: 'en_US', timeZone: 'America/Los_Angeles' }, }, factor: { id: 'smsigwDlH85L9FyQK0g3', factorType: 'sms', provider: 'OKTA', profile: { phoneNumber: '+1 XXX-XXX-6688' } }, verify: function(options) { /* returns another transaction */ }, poll: function() { /* returns another transaction */ }, prev: function() { /* returns another transaction */ }, cancel: function() { /* terminates the auth flow */ }, data: { /* the parsed json response */ } } ``` -------------------------------- ### IDX Transaction Steps Source: https://github.com/okta/okta-auth-js/blob/master/docs/migrate-from-authn-to-idx.md Illustrates the sequence of calls for an IDX transaction. The `start()` method initiates the flow, followed by `proceed()` with specific inputs like username or password to advance the transaction. ```javascript start(); // nextStep.inputs: [username] proceed({username: 'user@foo.com'}); // nextStep.inputs: [password] proceed({password: '12345}); ``` -------------------------------- ### Initiate Login Flow Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/app/public/static/index.html Starts the login process by redirecting the user to the Okta authorization server. The state parameter is used to maintain context across the redirect. ```javascript function login(e) { e.preventDefault(); authClient.token.getWithRedirect({ state: JSON.stringify({ issuer: issuer, clientId: clientId }) }); }; ``` -------------------------------- ### idx.startTransaction Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Starts a new transaction within an IDX flow. ```APIDOC ## idx.startTransaction ### Description Starts a new transaction within an IDX flow. ### Method APIDOC ### Endpoint APIDOC ### Parameters APIDOC ### Request Example APIDOC ### Response APIDOC ``` -------------------------------- ### Start Password Recovery (Up-Front) Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Initiates a password recovery flow by providing the username and desired authenticator. Use this when the username is known beforehand. ```javascript const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'verificationCode', ... }] } } = await authClient.idx.recoverPassword({ username: 'xxx', authenticators: [AuthenticatorKey.OKTA_EMAIL /* 'okta_email' */] }); // submit verification code const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'password', ... }] } } = await authClient.idx.proceed({ verificationCode: 'xxx' }); // submit new password const { status, // IdxStatus.SUCCESS tokens } = await authClient.idx.proceed({ password: 'xxx' }); ``` -------------------------------- ### Start IDX Transaction Source: https://github.com/okta/okta-auth-js/blob/master/docs/migrate-from-authn-to-idx.md Initiates an IDX transaction to begin the authentication flow. The `nextStep.inputs` will contain the required fields for the next step. ```javascript const { nextStep } = await idx.start(); // nextStep.inputs = [{ name: 'username', ... }, { name: 'password', ... }] const { status } = await idx.proceed({username: 'foo', password: 'bar'}); // status = IdxStatus.SUCCESS ``` -------------------------------- ### Start Account Unlock (Up-Front) Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Initiates an account unlock flow by providing the username and desired authenticator. Use this when the username is known beforehand. ```javascript const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'verificationCode', ... }] } } = await authClient.idx.unlockAccount({ username: 'xxx', authenticators: [AuthenticatorKey.OKTA_EMAIL /* 'okta_email' */] }); // submit verification code const { status, // IdxStatus.TERMINAL messages // 'Your Account is now unlocked!' } = await authClient.idx.proceed({ verificationCode: 'xxx' }); ``` -------------------------------- ### Get Tokens with Popup Source: https://github.com/okta/okta-auth-js/blob/master/README.md Creates tokens using a popup window for authentication. The popup first loads the web app at `initialPath` (defaults to '/') before redirecting to the authorization server to reduce blocking. ```javascript authClient.token.getWithPopup(options) .then(function(res) { var tokens = res.tokens; // Do something with tokens, such as authClient.tokenManager.setTokens(tokens); }) .catch(function(err) { // handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state) }); ``` -------------------------------- ### Example Commit Message for Breaking Change Source: https://github.com/okta/okta-auth-js/blob/master/CONTRIBUTING.md Illustrates how to format a commit message for a breaking change. The 'BREAKING CHANGE:' indicator must be at the beginning of the commit body. ```text feat: Allows provided config object to extend other configs BREAKING CHANGE: `extends` key in config file is now used for extending other config files ``` -------------------------------- ### DPoP-Protected Resource Request Example Source: https://github.com/okta/okta-auth-js/blob/master/README.md Illustrates the HTTP headers required for a DPoP-protected resource request, including the `Authorization` header with the DPoP token and the `DPoP` header with the proof. ```http GET /protectedresource HTTP/1.1 Host: resource.example.org Authorization: DPoP Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxU DPoP: eyJ0eXAiOiJkcG9wK2p3dCIsIm... ``` -------------------------------- ### Start Build:esm Task Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/tree-shaking/README.md Execute this command in a separate terminal to initiate the build:esm task with watch mode enabled. This ensures that changes are reflected in the bundle analysis. ```bash yarn build:esm --watch ``` -------------------------------- ### Initialize Auth State and Subscribe Source: https://github.com/okta/okta-auth-js/blob/master/README.md Trigger an initial authState change event when the app starts up by calling updateAuthState. Ensure this is done only if not in a login redirect flow. ```javascript authClient.authStateManager.subscribe(authState => { // handle emitted latest authState }); if (!authClient.isLoginRedirect()) { // Trigger an initial authState change event when the app startup authClient.authStateManager.updateAuthState(); } ``` -------------------------------- ### Run a Sample App Source: https://github.com/okta/okta-auth-js/blob/master/samples/README.md Navigate to a specific sample directory and run it using yarn. This is useful for testing individual samples. ```bash cd samples/generated/sample-name yarn start ``` ```bash yarn workspace {generatedSamplePkgName} start ``` -------------------------------- ### Get Current IDX Flow Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Retrieves the identifier for the currently configured flow. This is typically set automatically when starting a transaction. ```typescript const flow: FlowIdentifier = authClient.idx.getFlow(); ``` -------------------------------- ### Basic Authentication with IDX API (Up-front) Source: https://github.com/okta/okta-auth-js/blob/master/docs/migrate-from-authn-to-idx.md Starts an IDX authentication flow by providing credentials directly in the initial call. This approach may result in multiple network calls to the IDX API. ```javascript const { status } = await authClient.idx.start({ username: 'some-username', password: 'some-password', }); // status = IdxStatus.SUCCESS ``` -------------------------------- ### Access MyAccount API via OktaAuth instance Source: https://github.com/okta/okta-auth-js/blob/master/docs/myaccount/README.md After including the Okta Auth JS library via CDN and creating an OktaAuth instance, access MyAccount API methods under the 'myaccount' namespace. This example shows how to retrieve emails. ```javascript const oktaAuth = new OktaAuth({ // config }); const emails = await oktaAuth.myaccount.getEmails(); ``` -------------------------------- ### Re-authenticate with Embedded Widget Source: https://github.com/okta/okta-auth-js/blob/master/docs/myaccount/README.md Configure and bootstrap the embedded widget for re-authentication by passing max_age and acr_values in authParams. This example shows how to initialize the widget with these parameters and start the authentication flow. ```javascript const { issuer, clientId, redirectUri, scopes } = oidcConfig; const widget = new OktaSignIn({ baseUrl: issuer.split('/oauth2')[0], clientId, redirectUri, authParams: { scopes, ...(maxAge && { maxAge }), ...(acrValues && { acrValues }), }, useInteractionCodeFlow: true, }); ``` -------------------------------- ### webfinger(options) Source: https://github.com/okta/okta-auth-js/blob/master/README.md Calls the Webfinger API and gets a response. The `resource` parameter is a URI that identifies the entity whose information is sought, currently only acct scheme is supported. The `rel` parameter is optional to request only a subset of the information. ```APIDOC ## webfinger(options) ### Description Calls the [Webfinger](https://tools.ietf.org/html/rfc7033) API and gets a response. ### Method `async` ### Parameters #### Path Parameters - **options** (object) - Required. - **resource** (string) - URI that identifies the entity whose information is sought, currently only acct scheme is supported (e.g acct:dade.murphy@example.com). - **rel** (string) - Optional parameter to request only a subset of the information that would otherwise be returned without the "rel" parameter. ### Request Example ```javascript authClient.webfinger({ resource: 'acct:john.joe@example.com', rel: 'okta:idp' }) .then(function(res) { // use the webfinger response to select an idp }) .catch(function(err) { console.error(err); }); ``` ``` -------------------------------- ### Authenticate: Two Factors Auth with Email Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Starts an authentication flow with email as the authenticator. Use 'Up-Front' for initial setup or 'On-Demand' to gather user inputs dynamically. The verification code submission should be in a separate request. ```javascript const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'verificationCode', ... }] } } = await authClient.idx.authenticate({ username: 'xxx', password: 'xxx', authenticators: [AuthenticatorKey.OKTA_EMAIL /* 'okta_email' */] }); // submit verification code from email const { status, // IdxStatus.SUCCESS tokens } = await authClient.idx.proceed({ verificationCode: 'xxx' }); ``` ```javascript // start the flow with no param const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'username', ... }, { name: 'password', ... }] } } = await authClient.idx.authenticate(); // gather user inputs const { status, // IdxStatus.PENDING nextStep: { inputs, // [{ name: 'authenticator', ... }] } } = await authClient.idx.proceed({ username: 'xxx', password: 'xxx' }); // a list of authenticators is shown and the user selects "email" const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'verificationCode', ... }] } } = await authClient.idx.proceed({ authenticator: AuthenticatorKey.OKTA_EMAIL /* 'okta_email' */ }); // gather verification code from email (this call should happen in a separated request) const { status, // IdxStatus.SUCCESS tokens } = await authClient.idx.proceed({ verificationCode: 'xxx' }); ``` -------------------------------- ### Initialize OktaAuth Client with Configuration Source: https://github.com/okta/okta-auth-js/blob/master/README.md Create an instance of the OktaAuth client, passing your application's configuration object, including issuer, clientId, and redirectUri. ```javascript var config = { issuer: 'https://{yourOktaDomain}/oauth2/default', clientId: 'GHtf9iJdr60A9IYrR0jw', redirectUri: 'https://acme.com/oauth2/callback/home', }; var authClient = new OktaAuth(config); ``` -------------------------------- ### Link Built SDK Locally Source: https://github.com/okta/okta-auth-js/blob/master/README.md Navigate to the `build` folder to create a link for the built package. Then, in your project, link the SDK as a dependency. ```bash cd build yarn link cd ../../other yarn link @okta/okta-auth-js ``` -------------------------------- ### Main Application Startup Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/app/public/static/index.html The main function orchestrates the application's startup logic, including client initialization, redirect handling, and displaying user information or the login form. ```javascript main(); ``` -------------------------------- ### Start a Password Recovery Transaction Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Starts a password recovery transaction. This is a convenience alias for `idx.startTransaction` with the `recoverPassword` flow specified. ```javascript // start a recoverPassword transaction await authClient.idx.startTransaction({ flow: 'recoverPassword' }) ``` -------------------------------- ### Generate All Samples Source: https://github.com/okta/okta-auth-js/blob/master/samples/README.md Build all available samples for the Okta Auth JS library. This command generates the sample applications from templates. ```bash yarn build ``` -------------------------------- ### Run All Sample Tests Source: https://github.com/okta/okta-auth-js/blob/master/samples/README.md Execute all tests for the sample applications. This command verifies the functionality of all provided samples. ```bash yarn test ``` -------------------------------- ### Initiate Login Flow and Handle Callback Source: https://github.com/okta/okta-auth-js/blob/master/README.md Demonstrates saving the current URL before initiating the login flow with `getWithRedirect` and then parsing tokens from the URL on the callback page using `parseFromUrl`, saving them, and restoring the original URL. ```javascript // On any page while unauthenticated. // Save URL sessionStorage.setItem('url', window.location.href); // Redirect to Okta authClient.token.getWithRedirect({ responseType: 'token' }); ``` ```javascript // On callback (redirectUri) page authClient.token.parseFromUrl() .then(function(res) { // Save token authClient.tokenManager.setTokens(res.tokens); // Read saved URL from storage const url = sessionStorage.getItem('url'); sessionStorage.removeItem('url'); // Restore URL window.location.assign(url); }) .catch(function(err) { // Handle OAuthError }); ``` -------------------------------- ### signInWithCredentials(options) Source: https://github.com/okta/okta-auth-js/blob/master/README.md Initiates the sign-in process using provided credentials. Refer to the authn API documentation for detailed options. ```APIDOC ## signInWithCredentials(options) ### Description Initiates the sign-in process using provided credentials. See [authn API](docs/authn.md#signinwithcredentials). ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ``` -------------------------------- ### signInWithCredentials(options) Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md Initiates the sign-in process using user credentials. ```APIDOC ## signInWithCredentials(options) ### Description Initiates the sign-in process for a user by providing their credentials. ### Parameters - **options** (object) - Required - An object containing user credentials and other sign-in related options. ``` -------------------------------- ### Start and Stop OktaAuth Service Source: https://github.com/okta/okta-auth-js/blob/master/README.md Manage the OktaAuth service lifecycle by calling `start()` after creation to enable features like token auto-renewal and `stop()` to terminate background processes. ```javascript var authClient = new OktaAuth(config); await authClient.start(); // start the service await authClient.stop(); // stop the service ``` -------------------------------- ### Configure App via URL Query Parameters Source: https://github.com/okta/okta-auth-js/blob/master/samples/generated/express-web-with-oidc/README.md Pass configuration parameters directly to the app through the URL to avoid the initial configuration form. Ensure all query parameters are URL-encoded. ```html http://localhost:8080/?issuer=https%3A%2F%2Fabc.oktapreview.com%2Foauth2%2Fdefault ``` -------------------------------- ### get() Source: https://github.com/okta/okta-auth-js/blob/master/docs/myaccount/classes/EmailTransaction.md Retrieves the current transaction details. ```APIDOC ## get() ### Description Retrieves the current transaction details. ### Returns - `Promise` - A promise that resolves with the EmailTransaction details. ``` -------------------------------- ### get Source: https://github.com/okta/okta-auth-js/blob/master/docs/myaccount/classes/PhoneTransaction.md Retrieves the current phone transaction details. ```APIDOC ## get() ### Description Retrieves the current phone transaction details. This can be used to check the status or other properties of the ongoing transaction. ### Returns - `Promise` - A promise that resolves with the PhoneTransaction object. ``` -------------------------------- ### Configure Test App via URL Parameters Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/app/README.md Pass configuration parameters as encoded query parameters in the URL. If any query parameters are provided, all parameters are read from the URL, ignoring environment variables. ```html http://localhost:8080/?issuer=https%3A%2F%2Fabc.oktapreview.com%2Foauth2%2Fdefault&clientId=01234567xcdfgC80h7&pkce=false=openid,email&responseType=id_token,token ``` -------------------------------- ### Initialize OktaAuth Client Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/app/public/static/index.html Instantiate the OktaAuth client with issuer, clientId, and redirectUri. Ensure these values are correctly configured for your Okta application. ```javascript var authClient; var issuer; var clientId; var redirectUri = window.location.origin + window.location.pathname; // http://localhost:8080/static/ var url = new URL(window.location.href); var state = url.searchParams.get('state'); if (state) { state = JSON.parse(state); issuer = state.issuer; clientId = state.clientId; } else { issuer = url.searchParams.get('issuer'); clientId = url.searchParams.get('clientId'); } function main() { try { authClient = new OktaAuth({ issuer: issuer, clientId: clientId, redirectUri: redirectUri }); } catch (error) { return showError(error); } if (authClient.token.isLoginRedirect()) { return handleLoginRedirect(); } // normal app startup. showUserInfo(); } ``` -------------------------------- ### session.get Source: https://github.com/okta/okta-auth-js/blob/master/README.md Gets the active Okta session. Returns a promise that resolves with the session object. Requires access to third-party cookies. ```APIDOC ## `session.get()` ### Description Gets the active [session](https://developer.okta.com/docs/api/resources/sessions#example). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript authClient.session.get() .then(function(session) { // logged in }) .catch(function(err) { // not logged in }); ``` ### Response #### Success Response (200) - **session** (object) - The active session object. #### Response Example None ``` -------------------------------- ### Set IDX Flow Manually Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Manually sets the IDX flow. This method is useful when the flow is not automatically determined by starting a transaction. ```javascript authClient.idx.setFlow('register'); ``` -------------------------------- ### Configure OktaAuth Instance Source: https://github.com/okta/okta-auth-js/blob/master/README.md Initialize the OktaAuth library by providing the issuer URL for your Okta domain in the configuration object. ```javascript var OktaAuth = require('@okta/okta-auth-js').OktaAuth; var config = { // The URL for your Okta organization issuer: 'https://{yourOktaDomain}' }; var authClient = new OktaAuth(config); ``` -------------------------------- ### Build Specific Entry (App Directory) Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/verify-entries/README.md Run this command from within the test app directory to build a specific entry. ```sh yarn build:{entry} ``` -------------------------------- ### Cancel Authentication Flow Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md Asynchronously terminates the current authentication flow. This can be used to stop a transaction and potentially start a new one. ```javascript transaction.cancel() .then(function() { // transaction canceled. You can now start another with authClient.signIn }); ``` -------------------------------- ### MFA Enrollment Response Structure Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md This is an example of the response structure when MFA is required but the user is not enrolled. It lists available factors for enrollment. ```javascript { status: 'MFA_ENROLL', expiresAt: '2014-11-02T23:39:03.319Z', user: { id: '00ub0oNGTSWTBKOLGLNR', profile: { login: 'isaac@example.org', firstName: 'Isaac', lastName: 'Brock', locale: 'en_US', timeZone: 'America/Los_Angeles' } }, factors: [{ provider: 'OKTA', factorType: 'question', questions: function() { /* returns an array of possible questions */ }, enroll: function(options) { /* returns another transaction */ } }, { provider: 'OKTA', factorType: 'sms', enroll: function(options) { /* returns another transaction */ } }, { provider: 'OKTA', factorType: 'call', enroll: function(options) { /* returns another transaction */ } }, { provider: 'OKTA', factorType: 'push', enroll: function(options) { /* returns another transaction */ } }, { provider: 'OKTA', factorType: 'token:software:totp', enroll: function(options) { /* returns another transaction */ } }, { provider: 'GOOGLE', factorType: 'token:software:totp', enroll: function(options) { /* returns another transaction */ } }, { provider: 'YUBICO', factorType: 'token:hardware', enroll: function(options) { /* returns another transaction */ } }, { provider: 'RSA', factorType: 'token', enroll: function(options) { /* returns another transaction */ } }, { provider: 'SYMANTEC', factorType: 'token', enroll: function(options) { /* returns another transaction */ } }], cancel: function() { /* terminates the auth flow */ }, data: { /* the parsed json response */ } } ``` -------------------------------- ### Create OktaAuth Instance (Global) Source: https://github.com/okta/okta-auth-js/blob/master/README.md Instantiate the OktaAuth object globally after including the script from the CDN. Configuration options are passed during instantiation. ```javascript const oktaAuth = new OktaAuth({ // config }) ``` -------------------------------- ### Configure OktaAuth Client with DPoP Source: https://github.com/okta/okta-auth-js/blob/master/README.md Enable DPoP and configure its options when initializing the OktaAuth client. Ensure PKCE is also enabled. The `allowBearerTokens` option controls whether tokens are validated to include `token_type: DPoP`. ```javascript const config = { // other configurations pkce: true, // required dpop: true, dpopOptions: { // set to `true` to skip the validation to check the resulting token response includes `token_type: DPoP` allowBearerTokens: false // defaults to `false`, tokens are validated to include `token_type: DPoP` } }; const authClient = new OktaAuth(config); ``` -------------------------------- ### createOktaAuthMyAccount Source: https://github.com/okta/okta-auth-js/blob/master/docs/myaccount/modules.md Initializes the My Account module with the provided OktaAuth instance. ```APIDOC ## createOktaAuthMyAccount ### Description Initializes the My Account module. ### Parameters #### Parameters - **oktaAuth** (OktaAuthOAuthInterface) - Required - An instance of OktaAuth. - **options** (MyAccountRequestOptions) - Optional - Configuration options for the My Account module. ``` -------------------------------- ### Custom restoreOriginalUri Callback Source: https://github.com/okta/okta-auth-js/blob/master/README.md Implement `restoreOriginalUri` to override the default redirect behavior after authentication. This example shows how to use a custom router for redirection. ```javascript const config = { // other config restoreOriginalUri: async (oktaAuth, originalUri) => { // redirect with custom router router.replace({ path: toRelativeUrl(originalUri, baseUrl) }); } }; const oktaAuth = new OktaAuth(config); if (oktaAuth.isLoginRedirect()) { try { await oktaAuth.handleRedirect(); } catch (e) { // log or display error details } } ``` -------------------------------- ### Get Token from TokenManager Source: https://github.com/okta/okta-auth-js/blob/master/README.md Retrieves a token previously added to the TokenManager using its unique key. Handles token expiration and renewal status. ```javascript authClient.tokenManager.get('idToken') .then(function(token) { if (token && !authClient.tokenManager.hasExpired(token)) { // Token is valid console.log(token); } else { // Token has been removed due to expiration or error while renewing } }) .catch(function(err) { // handle OAuthError or AuthSdkError (AuthSdkError will be thrown if app is in OAuthCallback state) console.error(err); }); ``` -------------------------------- ### Example Response for Locked Out Status Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md Illustrates the structure of a transaction object when a user account is in a 'LOCKED_OUT' state. Includes methods to unlock or cancel the flow. ```javascript { status: 'LOCKED_OUT', unlock: function(options) { /* returns another transaction */ }, cancel: function() { /* terminates the auth flow */ }, data: { /* the parsed json response */ } } ``` -------------------------------- ### Configure SPA with URL Query Parameters Source: https://github.com/okta/okta-auth-js/blob/master/samples/generated/static-spa/README.md Pass configuration parameters like issuer and clientId directly in the URL to avoid the configuration form. Ensure all parameters are URL-encoded. ```html http://localhost:8080/?issuer=https%3A%2F%2Fabc.oktapreview.com%2Foauth2%2Fdefault&clientId=01234567xcdfgC80h7 ``` -------------------------------- ### Configure SPA with Query Parameters Source: https://github.com/okta/okta-auth-js/blob/master/samples/templates/partials/spa/README.md Pass configuration parameters directly to the app via URL query parameters to avoid the configuration form. Ensure all parameters are URL-encoded. ```html http://localhost:{{ port }}/?issuer=https%3A%2F%2Fabc.oktapreview.com%2Foauth2%2Fdefault&clientId=01234567xcdfgC80h7 ``` -------------------------------- ### Sign in with Credentials Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md Initiates a sign-in flow using username and password. Handles successful authentication by setting a session cookie and redirecting, or throws an error for other statuses. ```javascript authClient.signInWithCredentials({ username: 'some-username', password: 'some-password' }) .then(function(transaction) { if (transaction.status === 'SUCCESS') { authClient.session.setCookieAndRedirect(transaction.sessionToken); // Sets a cookie on redirect } else { throw 'We cannot handle the ' + transaction.status + ' status'; } }) .catch(function(err) { console.error(err); }); ``` -------------------------------- ### Configure OktaAuth with Custom Authorization Server Source: https://github.com/okta/okta-auth-js/blob/master/README.md Initializes the OktaAuth client using a custom authorization server ID. ```javascript var config = { issuer: 'https://{yourOktaDomain}/oauth2/custom-auth-server-id' }; var authClient = new OktaAuth(config); ``` -------------------------------- ### Build Specific Entry (Monorepo) Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/verify-entries/README.md Run this command from the root of the monorepo to build a specific entry of the test app. ```sh yarn workspace @okta/test.apps.verify-entries build:{entry} ``` -------------------------------- ### Perform Identify Step in Step Mode Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md In Step Mode, explicitly specify the remediation step to execute. This example shows how to perform the 'identify' step with a username. ```javascript const response = await idx.proceed({ step: 'identify', username: 'foo@bar.com' }) ``` -------------------------------- ### Configure OktaAuth with Default Authorization Server Source: https://github.com/okta/okta-auth-js/blob/master/README.md Initializes the OktaAuth client using the 'default' authorization server for your Okta domain. ```javascript var config = { issuer: 'https://{yourOktaDomain}/oauth2/default' }; var authClient = new OktaAuth(config); ``` -------------------------------- ### Forgot Password Flow Source: https://github.com/okta/okta-auth-js/blob/master/docs/authn.md Starts a password recovery process, verifies the recovery code, and resets the password. Upon successful reset, it sets a session cookie and redirects. ```javascript authClient.forgotPassword({ username: 'dade.murphy@example.com', factorType: 'SMS', }) .then(function(transaction) { // transaction.status == 'RECOVERY_CHALLENGE' return transaction.verify({ passCode: '123456' // The passCode from the SMS or CALL }); }) .then(function(transaction) { // transaction.status == 'PASSWORD_RESET' return transaction.resetPassword({ newPassword: 'N3wP4ssw0rd' }); }) .then(function(transaction) { if (transaction.status === 'SUCCESS') { authClient.session.setCookieAndRedirect(transaction.sessionToken); } else { throw 'We cannot handle the ' + transaction.status + ' status'; } }) .catch(function(err) { console.error(err); }); ``` -------------------------------- ### Custom transformAuthState Function Source: https://github.com/okta/okta-auth-js/blob/master/README.md Use `transformAuthState` to customize how the authentication state is processed. This example adds a check for a valid Okta SSO session and stores user information. ```javascript const config = { // other config transformAuthState: async (oktaAuth, authState) => { if (!authState.isAuthenticated) { return authState; } // extra requirement: user must have valid Okta SSO session const user = await oktaAuth.token.getUserInfo(); authState.isAuthenticated = !!user; // convert to boolean authState.users = user; // also store user object on authState return authState; } }; const oktaAuth = new OktaAuth(config); oktaAuth.authStateManager.subscribe(authState => { // handle latest authState }); oktaAuth.authStateManager.updateAuthState(); ``` -------------------------------- ### Configure Test App via Environment Variables Source: https://github.com/okta/okta-auth-js/blob/master/test/apps/app/README.md Optionally configure default values using environment variables from a 'testenv' file. These are used only if no query parameters are present in the URL. ```ini CLIENT_ID - abc12 ISSUER - x.okta.com/oauth2/default ``` -------------------------------- ### Run Individual Sample Test Source: https://github.com/okta/okta-auth-js/blob/master/samples/README.md Run tests for a specific sample by setting the SAMPLE_NAME environment variable. Replace 'webpack-spa' with the desired sample name. ```bash SAMPLE_NAME=webpack-spa ``` -------------------------------- ### Get All Tokens from TokenManager Source: https://github.com/okta/okta-auth-js/blob/master/README.md Retrieves all available tokens (access and ID) currently stored in the TokenManager, regardless of their storage keys. Returns an empty object if no tokens are present. ```javascript authClient.tokenManager.getTokens() .then(({ accessToken, idToken }) => { // handle accessToken and idToken }); ``` -------------------------------- ### Okta Auth JS Usage with TypeScript Source: https://github.com/okta/okta-auth-js/blob/master/README.md Demonstrates how to use Okta Auth JS with TypeScript, including importing types, configuring the client, and managing tokens and user info. ```typescript import { OktaAuth, OktaAuthOptions, TokenManagerInterface, AccessToken, IDToken, UserClaims, TokenParams } from '@okta/okta-auth-js'; const config: OktaAuthOptions = { issuer: 'https://{yourOktaDomain}' }; const authClient: OktaAuth = new OktaAuth(config); const tokenManager: TokenManagerInterface = authClient.tokenManager; const accessToken: AccessToken = await tokenManager.get('accessToken') as AccessToken; const idToken: IDToken = await tokenManager.get('idToken') as IDToken; const userInfo: UserClaims = await authClient.token.getUserInfo(accessToken, idToken); if (!userInfo) { const tokenParams: TokenParams = { scopes: ['openid', 'email', 'custom_scope'], }; authClient.token.getWithRedirect(tokenParams); } ``` -------------------------------- ### idx.startTransaction Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Resolves fields related to starting an IDX transaction. This serves as a single entry point for dynamic flows and provides metadata for integrations like the Okta Sign-In Widget. ```APIDOC ## `idx.startTransaction` Resolves [Start Transaction related fields](#start-transaction-related-fields). Popular use cases: - Single entry point when the [flow][] is dynamic - Provides `meta` for [Okta Sign-In Widget][] integration. - Provides `enabledFeatures` and `availableSteps` for dynamic UI rendering. ```javascript // start a recoverPassword transaction await authClient.idx.startTransaction({ flow: 'recoverPassword' }) ``` ``` -------------------------------- ### Start Password Recovery (On-Demand) Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Initiates a password recovery flow without a predefined username, allowing the user to input their username first. This is suitable for dynamic user input. ```javascript const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'username', ... }] } } = await authClient.idx.recoverPassword(); // gather username from user input const { status, // IdxStatus.PENDING nextStep: { inputs, // [{ name: 'authenticator', ... }] } } = await authClient.idx.proceed({ username }); // user sees a list of authenticators and selects "email" const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'verificationCode', ... }] } } = await authClient.idx.proceed({ authenticator: AuthenticatorKey.OKTA_EMAIL /* 'okta_email' */ }); // gather verification code from email (this call should happen in a separated request) const { status, nextStep: { inputs // [{ name: 'password', ...}] } } = await authClient.idx.proceed({ verificationCode: 'xxx' }); // submit new password const { status, // IdxStatus.SUCCESS tokens } = await authClient.idx.proceed({ password: 'xxx' }); ``` -------------------------------- ### Start Account Unlock (On-Demand) Source: https://github.com/okta/okta-auth-js/blob/master/docs/idx.md Initiates an account unlock flow without a predefined username, allowing the user to input their username and select an authenticator. This is suitable for dynamic user input. ```javascript const { status, // IdxStatus.PENDING nextStep: { inputs // [{ name: 'username', ... }] } } = await authClient.idx.unlockAccount(); // gather username from user input and // user sees a list of authenticators and selects "email" const { status, // IdxStatus.PENDING nextStep: { inputs, // [{ name: 'authenticator', ... }] } } = await authClient.idx.proceed({ username, authenticator: AuthenticatorKey.OKTA_EMAIL }); // gather verification code from email (this call should happen in a separated request) const { status, // IdxStatus.TERMINAL messages // 'Your Account is now unlocked!' } = await authClient.idx.proceed({ verificationCode: 'xxx' }); ``` -------------------------------- ### token.getWithIDPPopup(options) Source: https://github.com/okta/okta-auth-js/blob/master/README.md Authenticates a user using an external Identity Provider (IDP) in a popup window. This method is suitable for deployments that require popup authentication and interact with external IDPs, especially when stricter Cross-Origin-Opener-Policy headers are in use. It utilizes the `query` response mode and requires a `redirectUri` to handle the authentication callback. ```APIDOC ## token.getWithIDPPopup(options) ### Description Authenticates a user with an external Identity Provider (IDP) in a popup window. This method is designed for scenarios where popup authentication is necessary and external IDPs are involved, offering resilience against strict Cross-Origin-Opener-Policy configurations. It uses the `query` response mode, necessitating a `redirectUri` to complete the authentication flow by relaying the OAuth2 response. ### Method `token.getWithIDPPopup(options)` ### Parameters #### Options - **redirectUri** (string) - Required - The registered callback route URI where the authentication response will be sent. ### Request Example ```javascript const { promise, cancel } = authClient.token.getWithIDPPopup({ redirectUri: 'http://localhost:8080/popup/callback', }); const { tokens } = await promise; authClient.tokenManager.setTokens(tokens); ``` ### Response Returns an object containing a `promise` to await the authentication result and a `cancel` function to abort the process. #### Success Response - **tokens** - An object containing the authentication tokens. ```