### Create Bookmark Application with Okta SDK for Node.js Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a bookmark application in Okta. This example demonstrates providing request body parameters for application creation. Ensure the Okta SDK for Node.js is installed and configured with your organization URL and API token. ```typescript import { Application, ApplicationOptions } from '@okta/okta-sdk-nodejs/src/types/models/Application'; import { Client } from '@okta/okta-sdk-nodejs' import { LogEvent } from '@okta/okta-sdk-nodejs/src/types/models/LogEvent'; const client = new Client({ orgUrl:'https://dev-org.okta.com', token: 'apiToken', }); const bookmarkAppOptions: ApplicationOptions = { "name": "bookmark", "label": "Sample Bookmark App", "signOnMode": "BOOKMARK", "settings": { "app": { "requestIntegration": false, "url": "https://example.com/bookmark.htm" } } }; client.createApplication(bookmarkAppOptions).then((createdApp: Application) => { console.log(createdApp); }); ``` -------------------------------- ### Install Okta SDK for Node.js Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Install the Okta SDK for Node.js using npm. Requires Node.js version 4.8.3 or higher. ```sh npm install @okta/okta-sdk-nodejs ``` -------------------------------- ### Create Bookmark Application (5.1.0+) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a bookmark application using the `createApplication` method with explicit `ApplicationOptions`. This example is for versions 5.1.0 and later of the Okta SDK for Node.js. ```typescript const applicationOptions: ApplicationOptions = { name: 'bookmark', label: 'Bookmark app', signOnMode: 'BOOKMARK', settings: { app: { requestIntegration: false, url: 'https://example.com/bookmark.htm' } } }; const application: BookmarkApplication = client.createApplication(applicationOptions); ``` -------------------------------- ### OAuth 2.0 Authentication Setup Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Demonstrates how to construct an Okta client instance using OAuth 2.0 PrivateKey authentication for service-to-service applications. ```APIDOC ## OAuth 2.0 Authentication Setup This section details how to configure the Okta SDK client for OAuth 2.0 PrivateKey authentication, suitable for service-to-service applications. ### Configuration Parameters - **orgUrl** (string): The URL of your Okta organization. - **authorizationMode** (string): Set to 'PrivateKey' for OAuth 2.0 authentication. - **clientId** (string): The OAuth application ID. - **scopes** (array of strings): An array of scopes to request for the access token (e.g., ['okta.users.manage']). - **privateKey** (string or object): The private key in JWK JSON string, PEM format, or as a JWK object. - **keyId** (string): The key ID (kid) of the private key, required when `privateKey` is in PEM format or when multiple JWKs are used. ### Example Client Initialization ```javascript const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', authorizationMode: 'PrivateKey', clientId: '{oauth application ID}', scopes: ['okta.users.manage'], privateKey: '{JWK}', // or PEM string, or JWK object keyId: 'kidValue' }); ``` ### Private Key Formats The `privateKey` parameter can accept: - A JSON encoded string of a JWK object. - A string in PEM format. - A JSON object in JWK format. ### Key ID (kid) Handling - If the OAuth client app uses multiple JWKs, the `privateKey` should specify the `kid` attribute. - When `privateKey` is provided in PEM format, the `keyId` must be supplied in the SDK configuration. ### DPoP Support Starting from version 7.2.2, the Okta management SDK includes support for DPoP (Demonstrating Proof-of-Possession). If DPoP is enabled for the application, the SDK will automatically obtain a DPoP-bound access token and generate a new DPoP Proof JWT for each request without requiring additional developer configuration. ``` -------------------------------- ### Create An Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Allows you to create Okta Applications, with support for various types. This example demonstrates creating a Basic Authentication Application. ```APIDOC ## Create An Application The [Applications: Add Application] API allows you to create Okta Applications. There are many different types of applications that can be created. Please refer to the [Applications] documentation for details about each application type and what is required when creating the application. In this example, we create a [Basic Authentication Application]: ```javascript const application = { name: 'template_basic_auth', label: 'Sample Basic Auth App', signOnMode: 'BASIC_AUTH', settings: { app: { url: 'https://example.com/auth.htm', authURL: 'https://example.com/login.html' } } }; const createdApplication = await client.applicationApi.createApplication({ application }); console.log('Created application:', createdApplication); ``` ``` -------------------------------- ### Iterate Over User Collection (Serial/Parallel Synchronous) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Use the `each()` method on a user collection to process each user. This example logs each user and a final message after all users are visited. Ensure the `logUserToRemoteSystem` function is defined. ```javascript (await client.userApi.listUsers()).each(user => { console.log(user); logUserToRemoteSystem(user); }).then(() => { console.log('All users have been vistied'); }); ``` -------------------------------- ### Get System Log Events Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Query system log events starting from a specific date and time. This is useful for auditing and monitoring. ```javascript const collection = await client.systemLogApi.listLogEvents({ since: new Date('2018-01-25T00:00:00Z') }); ``` -------------------------------- ### Configure MemoryStore with Expiration Polling Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Example of configuring the `MemoryStore` with a `keyLimit` and enabling `expirationPoll` for proactive removal of expired keys. This is useful for distributed services. ```javascript const okta = require('@okta/okta-sdk-nodejs'); const MemoryStore = okta.MemoryStore; const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc', // Obtained from Developer Dashboard cacheStore: new MemoryStore({ keyLimit: 100000, expirationPoll: true }) }); ``` -------------------------------- ### Rebuild Auto-Generated Files Source: https://github.com/okta/okta-sdk-nodejs/blob/master/CONTRIBUTING.md Execute this command to regenerate SDK files based on the Open API spec after installing dev dependencies. ```sh yarn build ``` -------------------------------- ### Get logs Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves system log events, with options to filter by time and paginate results. ```APIDOC ## Get logs ### Description Queries system log events. Supports filtering by time and pagination. ### Method `client.systemLogApi.listLogEvents(queryOptions)` ### Parameters #### Body Parameters - **queryOptions** (object) - Optional - An object containing query parameters. - **since** (Date) - Optional - The starting point for fetching logs. ### Request Example ```javascript const collection = await client.systemLogApi.listLogEvents({ since: new Date('2018-01-25T00:00:00Z') }); ``` ### Collection Methods - **each(iterator)**: Iterates over all items in the collection. The iterator can be synchronous or asynchronous. Returning `false` stops iteration. Rejecting a promise stops iteration with an error. - **subscribe(config)**: Starts a subscription to poll for new log events at a specified interval. ``` -------------------------------- ### Get Application (v7.x.x) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves a specific application by its ID using the `applicationApi`. Requires an object with the `appId`. ```APIDOC ## GET /applications/{appId} ### Description Retrieves a specific application by its ID using the `applicationApi`. ### Method GET ### Endpoint /applications/{appId} ### Parameters #### Query Parameters - **appId** (string) - Required - The ID of the application to retrieve. ### Request Example ```typescript const oidcApp = await client.applicationApi.getApplication({ appId }); ``` ### Response #### Success Response (200) - **oidcApp** (OpenIdConnectApplication) - The requested application object. ``` -------------------------------- ### Get Application using API Object (7.x.x) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves an OpenID Connect application using the `client.applicationApi.getApplication` method in version 7.x.x and later. Parameters are passed as a single object. Requires an `await` call. ```typescript const oidcApp: OpenIdConnectApplication = await client.applicationApi.getApplication({ appId }); ``` -------------------------------- ### Get a User Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Fetches a user by their ID or login name using the `getUser` method. ```APIDOC ## Get a User ### Description Fetches a user by their ID or login name. ### Method `client.userApi.getUser({ userId: :id|:login })` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID or login name of the user to retrieve. ### Request Example ```javascript client.userApi.getUser({ userId: 'ausmvdt5xg8wRVI1d0g3' }).then(user => { console.log(user); }); client.userApi.getUser({ userId: 'foo@bar.com' }).then(user => { console.log(user); }); ``` ### Response #### Success Response (200) - **user** (object) - The user object. ``` -------------------------------- ### Get Application by ID with Okta SDK for Node.js (5.1.0+) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves an application by its ID using the `getApplication` method. This method can be parameterized with the application type for better type safety. Requires the Okta SDK for Node.js. ```typescript const oidcApp: OpenIdConnectApplication = client.getApplication(appId); ``` ```typescript const oidcApp: OpenIdConnectApplication = client.getApplication(appId); ``` -------------------------------- ### Custom Cache Store Interface Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Defines the interface for creating a custom cache store. Implement the `get`, `set`, and `delete` methods. ```javascript class CustomStore { async get(stringKey) {} async set(stringKey, stringValue) {} async delete(stringKey) {} } ``` -------------------------------- ### Get Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves a specific application by its ID. This method can be parameterized with the application type for more specific typing. ```APIDOC ## GET /applications/{appId} ### Description Retrieves a specific application by its ID. ### Method GET ### Endpoint /applications/{appId} ### Parameters #### Path Parameters - **appId** (string) - Required - The ID of the application to retrieve. ### Request Example ```typescript // For typed retrieval const oidcApp = client.getApplication(appId); // For standard retrieval const application = client.getApplication(appId); ``` ### Response #### Success Response (200) - **application** (Application) - The requested application object. ``` -------------------------------- ### Get a Session Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieve details about an existing session using its ID. The returned details include authentication information and expiration. ```javascript session = await client.sessionApi.getSession({ sessionId: session.id }); console.log('Session details:', session); ``` -------------------------------- ### Disable Cache Middleware Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Example of disabling the default cache middleware by setting `cacheMiddleware` to `null` in the client constructor. ```javascript const okta = require('@okta/okta-sdk-nodejs'); const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc', // Obtained from Developer Dashboard cacheMiddleware: null }); ``` -------------------------------- ### Get a User Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Fetches a user from Okta by their user ID or login name. This operation corresponds to the Okta Platform API's 'Users: Get User' endpoint. ```APIDOC ## Get a User Fetches a user from Okta by their user ID or login name. This method wraps the Okta Platform API's 'Users: Get User' endpoint. ### Method `client.userApi.getUser({ userId })` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID or login name of the user to retrieve. ### Request Example ```javascript // Get user by ID let user = await client.userApi.getUser({ userId: 'ausmvdt5xg8wRVI1d0g3' }); console.log(user); // Get user by login name user = await client.userApi.getUser({ userId: 'foo@bar.com' }); console.log(user); ``` ### Response #### Success Response (200) - **user** (object) - The user object. ``` -------------------------------- ### Get a Session Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves details about a session using its ID with the `client.sessionApi.getSession()` method. Details include authentication information and expiration. ```APIDOC ## Get a Session To retrieve details about a session, you must know the ID of the session: ```javascript session = await client.sessionApi.getSession({ sessionId: session.id }); console.log('Session details:', session); ``` These details include when and how the user authenticated and the session expiration. For more information see [Sessions: Session Properties] and [Sessions: Session Operations]. ``` -------------------------------- ### Get Logs Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Retrieves log events from Okta. The `getLogs` method can be filtered by a `since` parameter to fetch events after a specific date. ```APIDOC ## GET /logs ### Description Retrieves log events from Okta. ### Method GET ### Endpoint /logs ### Parameters #### Query Parameters - **since** (string) - Optional - Fetch events since this date. ### Request Example ```typescript import { Client } from '@okta/okta-sdk-nodejs' const client = new Client({ orgUrl:'https://dev-org.okta.com', token: 'apiToken', }); const logEvents = client.getLogs({ since: '2021-03-11' }); ``` ### Response #### Success Response (200) - **logEvents** (AsyncIterable) - An iterable of log event objects. ``` -------------------------------- ### Get a User by ID or Login with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Fetch a user from Okta by their ID or login name using the `getUser` method. The `userId` parameter accepts either the user's ID or their `profile.login` value. ```javascript client.userApi.getUser({ userId: 'ausmvdt5xg8wRVI1d0g3' }).then(user => { console.log(user); }); client.userApi.getUser({ userId: 'foo@bar.com' }).then(user => { console.log(user); }); ``` -------------------------------- ### Create Application using API Object (7.x.x) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a bookmark application using the `client.applicationApi.createApplication` method in version 7.x.x and later. Parameters are passed as a single object. Requires an `await` call. ```typescript const application: BookmarkApplication = { name: 'bookmark', label: 'Bookmark app', signOnMode: 'BOOKMARK', settings: { app: { requestIntegration: false, url: 'https://example.com/bookmark.htm' } } }; const createdApplication: BookmarkApplication = await client.applicationApi.createApplication({ application }); ``` -------------------------------- ### Okta Client Configuration (Environment Variables) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Configure the Okta client using environment variables. Configuration names are flattened and delimited with underscores. ```sh OKTA_CLIENT_ORGURL=https://dev-1234.oktapreview.com/ OKTA_CLIENT_TOKEN=xYzabc ``` -------------------------------- ### Okta Client Configuration (YAML) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Configure the Okta client using a YAML file. The structure should match the properties passed to the client constructor. ```yaml okta: client: orgUrl: 'https://dev-1234.oktapreview.com/' token: 'xYzabc' ``` -------------------------------- ### Create Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a new application in Okta. This method accepts an `ApplicationOptions` object to define the application's properties, such as name, label, and sign-on mode. ```APIDOC ## POST /applications ### Description Creates a new application in Okta. ### Method POST ### Endpoint /applications ### Parameters #### Request Body - **applicationOptions** (ApplicationOptions) - Required - Configuration for the new application. - **name** (string) - Required - The name of the application. - **label** (string) - Required - The display label for the application. - **signOnMode** (string) - Required - The sign-on mode for the application (e.g., 'BOOKMARK'). - **settings** (object) - Required - Application-specific settings. - **app** (object) - Required - Settings for the application. - **requestIntegration** (boolean) - Required - Whether to request integration. - **url** (string) - Required - The URL for bookmark applications. ### Request Example ```typescript import { Client } from '@okta/okta-sdk-nodejs' const client = new Client({ orgUrl:'https://dev-org.okta.com', token: 'apiToken', }); const bookmarkAppOptions = { "name": "bookmark", "label": "Sample Bookmark App", "signOnMode": "BOOKMARK", "settings": { "app": { "requestIntegration": false, "url": "https://example.com/bookmark.htm" } } }; client.createApplication(bookmarkAppOptions).then((createdApp) => { console.log(createdApp); }); ``` ### Response #### Success Response (200) - **createdApp** (Application) - The newly created application object. ``` -------------------------------- ### Create Application (v7.x.x) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a new application using the `applicationApi`. This method requires an object containing the application configuration. ```APIDOC ## POST /applications ### Description Creates a new application using the `applicationApi`. ### Method POST ### Endpoint /applications ### Parameters #### Request Body - **application** (object) - Required - The application configuration object. - **name** (string) - Required - The name of the application. - **label** (string) - Required - The display label for the application. - **signOnMode** (string) - Required - The sign-on mode for the application. - **settings** (object) - Required - Application-specific settings. - **app** (object) - Required - Settings for the application. - **requestIntegration** (boolean) - Required - Whether to request integration. - **url** (string) - Required - The URL for bookmark applications. ### Request Example ```typescript const application = { name: 'bookmark', label: 'Bookmark app', signOnMode: 'BOOKMARK', settings: { app: { requestIntegration: false, url: 'https://example.com/bookmark.htm' } } }; const createdApplication = await client.applicationApi.createApplication({ application }); ``` ### Response #### Success Response (200) - **createdApplication** (BookmarkApplication) - The newly created application object. ``` -------------------------------- ### Create a User with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Create a new user in Okta using the `createUser` method. The user object must include profile information and credentials. ```javascript const newUser = { profile: { firstName: 'Foo', lastName: 'Bar', email: 'foo@example.com', login: 'foo@example.com', }, credentials: { password : { value: 'PasswordAbc123' } } }; client.userApi.createUser({ body: newUser }) .then(user => { console.log('Created user', user); }); ``` -------------------------------- ### Create a Basic Authentication Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Create a new Okta application of type 'BASIC_AUTH'. This requires specifying the application's name, label, sign-on mode, and relevant settings. ```javascript const application = { name: 'template_basic_auth', label: 'Sample Basic Auth App', signOnMode: 'BASIC_AUTH', settings: { app: { url: 'https://example.com/auth.htm', authURL: 'https://example.com/login.html' } } }; const createdApplication = await client.applicationApi.createApplication({ application }); console.log('Created application:', createdApplication); ``` -------------------------------- ### Run Integration Tests Source: https://github.com/okta/okta-sdk-nodejs/blob/master/CONTRIBUTING.md Execute this command to run the integration tests after configuring the necessary environment variables. ```sh yarn test ``` -------------------------------- ### Configure Environment Variables for Testing Source: https://github.com/okta/okta-sdk-nodejs/blob/master/CONTRIBUTING.md Set these environment variables with your Okta domain and API token to run integration tests against a live Okta organization. ```bash OKTA_CLIENT_ORGURL=https://{yourOktaDomain}.com/ OKTA_CLIENT_TOKEN=xxxx_api_token ``` -------------------------------- ### Create Okta SDK Client Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Initialize the Okta SDK client with your Okta organization URL and an API token. The token can be obtained from the Okta Developer Dashboard. ```javascript const okta = require('@okta/okta-sdk-nodejs'); const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc' // Obtained from Developer Dashboard }); ``` -------------------------------- ### Import Models from Library Root (>=4.6.x) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Demonstrates importing models like Client and LogEvent directly from the library root in versions 4.6.x and later of the Okta SDK for Node.js. ```typescript import { Client, LogEvent } from '@okta/okta-sdk-nodejs'; ``` -------------------------------- ### Initialize Okta Client with OAuth 2.0 PrivateKey Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Construct a client instance for OAuth 2.0 PrivateKey authorization. This method is used for service-to-service applications and does not require an API Token. ```javascript const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', authorizationMode: 'PrivateKey', clientId: '{oauth application ID}', scopes: ['okta.users.manage'], privateKey: '{JWK}', // <-- see notes below keyId: 'kidValue' }); ``` -------------------------------- ### List All Org Users with each() Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Use the `each()` method to iterate through a collection of users. This is useful for processing large numbers of users. ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); }); console.log('All users have been listed'); ``` -------------------------------- ### Create a User Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Creates a new user in the Okta organization using the `createUser` method. Requires user profile and credentials. ```APIDOC ## Create a User ### Description Creates a new user in the Okta organization. ### Method `client.userApi.createUser({ body: newUser })` ### Parameters #### Request Body - **body** (object) - Required - An object containing the new user's profile and credentials. - **profile** (object) - Required - User's profile information. - **firstName** (string) - Required - User's first name. - **lastName** (string) - Required - User's last name. - **email** (string) - Required - User's email address. - **login** (string) - Required - User's login name. - **credentials** (object) - Required - User's login credentials. - **password** (object) - Required - User's password details. - **value** (string) - Required - The user's password. ### Request Example ```javascript const newUser = { profile: { firstName: 'Foo', lastName: 'Bar', email: 'foo@example.com', login: 'foo@example.com', }, credentials: { password : { value: 'PasswordAbc123' } } }; client.userApi.createUser({ body: newUser }) .then(user => { console.log('Created user', user); }); ``` ### Response #### Success Response (200) - **user** (object) - The created user object. ``` -------------------------------- ### Create a Session Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Creates a user session using a session token. This is a rarely used method, with `Create Session with Session Token` being the more common approach. ```APIDOC ## Create a Session This is a rarely used method. See [Sessions: Create Session with Session Token] for the common ways to create a session. To use this method, you must have a sessionToken: ```javascript const session = await client.sessionApi.createSession({ createSessionRequest: { sessionToken: 'your session token' } }); console.log('Session details:', session); ``` ``` -------------------------------- ### Create a Session Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Create a new user session using a session token. This is a less common method; refer to 'Create a Session with Session Token' for typical usage. ```javascript const session = await client.sessionApi.createSession({ createSessionRequest: { sessionToken: 'your session token' } }); console.log('Session details:', session); ``` -------------------------------- ### Search Users by Query Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Search for users using the `q` parameter for general queries. The library handles URL encoding for you. ```javascript let collection; collection = await client.userApi.listUsers({ q: 'Robert' }); await collection.each(user => { console.log('User matches query: ', user); }); ``` -------------------------------- ### Assign a User to an Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Assign a user to an application using their IDs. This creates an application-specific user instance. ```javascript const appUser = await client.applicationApi.assignUserToApplication({ appId: createdApplication.id, appUser: { id: createdUser.id } }); console.log('Assigned user to app, app user instance:', appUser); ``` -------------------------------- ### Configure Client with Custom Cache Buffer Size Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Configures the Okta SDK client with a custom `defaultCacheMiddlewareResponseBufferSize` to mitigate stream internal buffer size limitations. This is a workaround and should be used with caution. ```typescript const client: Client = new Client({ orgUrl: 'https://orgname.okta.com', token: 'apiToken', defaultCacheMiddlewareResponseBufferSize: sizeInBytes }); ``` -------------------------------- ### Create a Group Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Allows you to create Groups using the `client.groupApi.createGroup()` method. ```APIDOC ## Create a Group The [Groups: Add Group] API allows you to create Groups, and this is wrapped by `client.groupApi.createGroup({ group })`: ```javascript const newGroup = { profile: { name: 'Admin Users Group' } }; const group = await client.groupApi.createGroup({ group: newGroup }); console.log('Created group', group); ``` ``` -------------------------------- ### List All Org Users Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Fetches collections of users and allows iteration using `each()` or async iterators. ```APIDOC ## List All Org Users The client can be used to fetch collections of resources, in this example we'll use the [Users: List Users] API. When fetching collections, you can use the `each()` method to iterate through the collection. For more information see [Collection](#collection). ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); }); console.log('All users have been listed'); ``` You can also use async iterators. ```javascript const collection = await client.userApi.listUsers(); for await (let user of collection) { console.log(user); } ``` For more information about this API see [Users: Get User]. ``` -------------------------------- ### Create a Group with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Create a new group in Okta using the `createGroup` method. The group object requires a `profile` property with a `name` for the group. ```javascript const newGroup = { profile: { name: 'Admin Users Group' } }; client.groupApi.createGroup({grpup: newGroup}) .then(group => { console.log('Created group', group); }); ``` -------------------------------- ### Search Users by Query, Filter, or Search String with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Search for users using different criteria: a general query string (`q`), a filter expression (`filter`), or a more advanced search string (`search`). The SDK handles URL encoding for these parameters. ```javascript await (await client.userApi.listUsers({ q: 'Robert' })).each(user => { console.log('User matches query: ', user); }); await (await client.userApi.listUsers({ search: 'profile.nickName eq "abc 1234"' })).each(user => { console.log('User matches search:', user); }); await (await client.userApi.listUsers({ filter: 'lastUpdated gt "2017-06-05T23:00:00.000Z"' })).each(user => { console.log('User matches filter:', user); }); ``` -------------------------------- ### Build and Validate Generated Code Source: https://github.com/okta/okta-sdk-nodejs/blob/master/CONTRIBUTING.md Run these commands to build and validate code generated from the API spec. Use `build:fixSpec` to maintain backward compatibility. ```sh yarn build:fixSpec # run this if you want to keep changes backward compatible yarn build:validateGenerated ``` -------------------------------- ### Search Users by Search String Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Search for users using the `search` parameter with Okta's search syntax. The library handles URL encoding for you. ```javascript collection = await client.userApi.listUsers({ search: 'profile.nickName eq "abc 1234"' }); await collection.each(user => { console.log('User matches query: ', user); }); ``` -------------------------------- ### Configure HTTPS Proxy Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Configure the Okta client to use an HTTPS proxy by providing the 'httpsProxy' property. The client will use environment variables 'https_proxy' or 'HTTPS_PROXY' if this is not overridden. ```javascript const okta = require('@okta/okta-sdk-nodejs'); const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc', // Obtained from Developer Dashboard httpsProxy: 'http://proxy.example.net:8080/' }); ``` -------------------------------- ### Validate Generated APIs Source: https://github.com/okta/okta-sdk-nodejs/blob/master/CONTRIBUTING.md Run this command to check for new APIs added to the spec that are missing in the current client. ```sh yarn build:validateGenerated ``` -------------------------------- ### List All Org Users Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Fetches a collection of all users in the Okta organization using `listUsers`. The `each()` method can be used to iterate through the collection. ```APIDOC ## List All Org Users ### Description Fetches a collection of all users in the Okta organization. ### Method `client.userApi.listUsers()` ### Request Example ```javascript const orgUsersCollection = client.userApi.listUsers(); orgUsersCollection.each(user => { console.log(user); }) .then(() => console.log('All users have been listed')); ``` ### Response #### Success Response (200) - **orgUsersCollection** (Collection) - A collection object that can be iterated over to retrieve user objects. ``` -------------------------------- ### Create a Group Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Creates a new group in the Okta organization using the `createGroup` method. Requires a group object with a name. ```APIDOC ## Create a Group ### Description Creates a new group in the Okta organization. ### Method `client.groupApi.createGroup({ grpup: newGroup })` ### Parameters #### Request Body - **grpup** (object) - Required - An object containing the new group's profile. - **profile** (object) - Required - Group's profile information. - **name** (string) - Required - The name of the group. ### Request Example ```javascript const newGroup = { profile: { name: 'Admin Users Group' } }; client.groupApi.createGroup({grpup: newGroup}) .then(group => { console.log('Created group', group); }); ``` ### Response #### Success Response (200) - **group** (object) - The created group object. ``` -------------------------------- ### Configure User Agent Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Specify a custom User-Agent string for client requests by using the 'userAgent' property. This string will be prepended to the SDK's default user agent. ```javascript const okta = require('@okta/okta-sdk-nodejs'); const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc', // Obtained from Developer Dashboard userAgent: 'example/1.0' }); ``` -------------------------------- ### Client Configuration with Cache Buffer Size Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Configures the Okta client with a custom response buffer size for the default cache middleware to mitigate stream internal buffer size limitations. ```APIDOC ## Client Configuration ### Description Allows configuring the Okta client with a custom `defaultCacheMiddlewareResponseBufferSize` to address Node.js stream limitations. ### Parameters #### Client Configuration Object - **orgUrl** (string) - Required - The Okta organization URL. - **token** (string) - Required - The API token. - **defaultCacheMiddlewareResponseBufferSize** (number) - Optional - Custom buffer size in bytes for the default cache middleware. ### Request Example ```typescript const client = new Client({ orgUrl: 'https://orgname.okta.com', token: 'apiToken', defaultCacheMiddlewareResponseBufferSize: sizeInBytes }); ``` ``` -------------------------------- ### Assign User to Group Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Use `client.groupApi.assignUserToGroup` to add a user to a specified group. Ensure you have user and group instances available. ```javascript client.groupApi.assignUserToGroup({groupId: group.id, userId: user.id}).then(() => console.log('User has been added to group')); ``` -------------------------------- ### Subscribe to System Log Events Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Subscribe to system log events to receive new logs as they arrive. Configure an interval for polling and define callbacks for new log items, errors, and completion. ```javascript const collection = await client.systemLogApi.listLogEvents({ since: new Date('2018-01-24T23:00:00Z') }); const subscription = collection.subscribe({ interval: 5000, // Time in ms before fetching new logs when all existing logs are read next(logItem) { // Do something with the logItem }, error(err) { // HTTP/Network Request errors are given here // The subscription will continue unless you call subscription.unsubscribe() }, complete() { // Triggered when subscription.unsubscribe() is called } }); ``` -------------------------------- ### `each()` Collection Method Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Iterates over all items in a collection, allowing for synchronous or asynchronous processing of each item. ```APIDOC ## `each()` Collection Method ### Description Iterates over every item in a collection. The iteration can be paused or stopped by returning a promise or `false` from the iterator function. ### Method `collection.each(iterator)` ### Parameters #### Path Parameters - **iterator** (function) - Required - A function to execute for each item in the collection. It can be synchronous or asynchronous. ### Behavior - If the iterator returns a promise, iteration pauses until the promise resolves. - Returning `false` from the iterator (or a resolved promise returning `false`) stops iteration. - Rejecting a promise from the iterator stops iteration with an error. ### Examples #### Serial or Parallel Synchronous Work ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); logUserToRemoteSystem(user); }); console.log('All users have been visited'); ``` #### Serial Asynchronous Work ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { return new Promise((resolve, reject) => { // do work, then resolve or reject the promise }); }); ``` #### Ending Iteration ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); return false; }); console.log('Only one user was visited'); ``` #### Ending Iteration with a Promise ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); return Promise.resolve(false); }); console.log('Only one user was visited'); ``` #### Ending Iteration with an Error ```javascript const collection = await client.userApi.listUsers(); collection.each(user => { console.log(user); return Promise.reject('foo error'); }) .catch(err => { console.log(err); // 'foo error' }); ``` ``` -------------------------------- ### Fetch Log Events with Okta SDK for Node.js Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Fetches log events from Okta and extracts actor display names. Requires the Okta SDK for Node.js. Ensure you have the correct organization URL and API token. ```typescript import { Client } from '@okta/okta-sdk-nodejs' import { LogEvent } from '@okta/okta-sdk-nodejs/src/types/models/LogEvent'; const client = new Client({ orgUrl:'https://dev-org.okta.com', token: 'apiToken', }); const logEvents = client.getLogs({ since: '2021-03-11' }); const actors: Set = new Set(); logEvents.each((entry: LogEvent) => { actors.add(entry.actor.displayName); }).then(() => { // res.send(JSON.stringify([...actors], null, 4)); };) ``` -------------------------------- ### List All Organization Users with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Retrieve all users in the Okta organization using the `listUsers` method and iterate through the collection using `each()`. This is useful for batch operations or reporting. ```javascript const orgUsersCollection = client.userApi.listUsers(); orgUsersCollection.each(user => { console.log(user); }) .then(() => console.log('All users have been listed')); ``` -------------------------------- ### Assign a User to an Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Assigns a user to an application using their respective IDs with the `client.applicationApi.assignUserToApplication()` method, creating an application-specific user profile. ```APIDOC ## Assign a User to an Application To assign a user to an application, you must know the ID of the application and the user: ```javascript const appUser = await client.applicationApi.assignUserToApplication({ appId: createdApplication.id, appUser: { id: createdUser.id } }); console.log('Assigned user to app, app user instance:', appUser); ``` An App User is created, which is a new user instance that is specific to this application. An App User allows you define an application-specific profile for that user. For more information please see [Applications: User Operations] and [Applications: Application User Profile]. ``` -------------------------------- ### Use Base Request Executor Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Instantiate the Okta Client with an explicit Base Request Executor. This executor delegates requests to isomorphic-fetch and emits 'request' and 'response' events. ```javascript const client = new okta.Client({ orgUrl: 'https://dev-1234.oktapreview.com/', token: 'xYzabc', // Obtained from Developer Dashboard requestExecutor: new okta.RequestExecutor() }); ``` -------------------------------- ### Update a User with Okta SDK Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md Modify an existing user's profile and persist the changes using the `updateUser` method. Ensure you have a user instance obtained previously. ```javascript user.profile.nickName = 'rob'; client.userApi.updateUser({ userId: user.id, user }).then(() => console.log('User nickname change has been saved')); ``` -------------------------------- ### Iterate Through Collections with `each()` Source: https://github.com/okta/okta-sdk-nodejs/blob/master/docs/JSDOC.md The `each()` method on a collection allows for iterating over resources, supporting synchronous or asynchronous operations for each item. ```APIDOC ## each() ### Description Visits every item in a collection, allowing for custom work on each item. Returns a promise that resolves when all items are visited or rejects if the iterator returns a rejected promise. Iteration can be stopped by rejecting a promise or returning `false`. ### Usage - **Serial or Parallel Synchronous Work**: If no value is returned, `each()` continues to the next item. ```javascript (await client.userApi.listUsers()).each(user => { console.log(user); logUserToRemoteSystem(user); }).then(() => { console.log('All users have been visited'); }); ``` - **Serial Asynchronous Work**: Returning a promise pauses the iterator until the promise resolves. ```javascript (await client.userApi.listUsers()).each(user => { return new Promise((resolve, reject) => { // do work, then resolve or reject the promise }) }); ``` - **Ending Iteration**: Returning `false` or `Promise.resolve(false)` will end iteration. ```javascript (await client.userApi.listUsers()).each(user => { console.log(user); return false; }).then(() => { console.log('Only one user was visited'); }); ``` - **Ending Iteration with Error**: Rejecting a promise will end iteration with an error. ```javascript return (await client.userApi.listUsers()).each((user) => { console.log(user); return Promise.reject('foo error'); }).catch((err)=>{ console.log(err); // 'foo error' }); ``` ``` -------------------------------- ### List All Org Users with Async Iterator Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Alternatively, use async iterators to loop through user collections. This provides a more modern JavaScript approach to asynchronous iteration. ```javascript const collection = await client.userApi.listUsers(); for await (let user of collection) { console.log(user); } ``` -------------------------------- ### Iterate Users Serially/Parallel (Synchronous) Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Iterate over all users in a collection, performing synchronous work for each user. The `each()` method continues to the next item if no value is returned. ```javascript const collection = await client.userApi.listUsers(); await collection.each(user => { console.log(user); logUserToRemoteSystem(user); }); console.log('All users have been visited'); ``` -------------------------------- ### Assign a User to a Group Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Assign an existing user to an existing group using their respective IDs. This method requires both `groupId` and `userId`. ```javascript await client.groupApi.assignUserToGroup({ groupId: group.id, userId: user.id }); console.log('User has been added to group'); ``` -------------------------------- ### Configure Default Request Executor with Retries and Timeout Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Instantiate the DefaultRequestExecutor with custom maxRetries and requestTimeout values. This executor automatically retries requests that return a 429 error. ```javascript const customDefaultRequestExecutor = new okta.DefaultRequestExecutor({ maxRetries: 2, requestTimeout: 0 // Specify in milliseconds if needed }) const client = new okta.Client({ orgUrl: 'https://dev-1234.okta.com/', token: 'xYzabc', // Obtained from Developer Dashboard requestExecutor: customDefaultRequestExecutor }); ``` -------------------------------- ### Listen for Backoff and Resume Events Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Attach event listeners to the DefaultRequestExecutor to log retry attempts ('backoff') and when a retried request begins ('resume'). The 'requestId' and 'delayMs' are provided for convenience. ```javascript defaultRequestExecutor.on('backoff', (request, response, requestId, delayMs) => { console.log(`Backoff ${delayMs} ${requestId}, ${request.url}`); }); defaultRequestExecutor.on('resume', (request, requestId) => { console.log(`Resume ${requestId} ${request.url}`); }); ``` -------------------------------- ### Assign a Group to an Application Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Assign an existing group to an application using their respective IDs. An empty `applicationGroupAssignment` object is provided as a placeholder. ```javascript const assignment = await client.applicationApi.assignGroupToApplication({ appId: createdApplication.id, groupId: createdGroup.id, applicationGroupAssignment: {} }); console.log('Assignment:', assignment); ``` -------------------------------- ### Create Custom Request Executor by Extending DefaultExecutorWithLogging Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Extend the DefaultRequestExecutor to add custom logging for request duration, including retry time. The custom fetch method delegates to the superclass's fetch method. ```javascript class DefaultExecutorWithLogging extends okta.DefaultRequestExecutor { fetch(request) { const start = new Date(); console.log(`Begin request for ${request.url}`); return super.fetch(request).then(response => { const timeMs = new Date() - start; console.log(`Request complete for ${request.url} in ${timeMs}ms`); return response; }); } } const client = new okta.Client({ requestExecutor: new DefaultExecutorWithLogging() }) ``` -------------------------------- ### Listen for Request and Response Events Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Attach event listeners to the client's request executor to log outgoing requests ('request') and incoming responses ('response'). This is useful for debugging and request logging. ```javascript const client = new okta.Client({ // uses the base executor by default }); client.requestExecutor.on('request', (request) => { console.log(`Request ${request.url}`); }); client.requestExecutor.on('response', (response) => { console.log(`Response ${response.status}`); }); ``` -------------------------------- ### Subscribe to a Collection Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Use this to paginate a collection until new items are available. The System Log API is currently the only supported collection. To stop polling, call `unsubscribe()` on the returned subscription object. ```javascript const subscription = collection.subscribe({ interval: 5000, next(item) { console.log(item); }, error(err) { // handle error } }); // In the future, unsubscribe when you want to stop polling: subscription.unsubscribe() ``` -------------------------------- ### Handle 429 Rate Limit Errors in Node.js Source: https://github.com/okta/okta-sdk-nodejs/blob/master/README.md Catch 429 errors from the Okta API and parse the 'x-rate-limit-reset' header to determine the retry time. Calculate the delay by comparing the reset time with the current 'date' header, adding a small buffer. ```javascript client.userApi.createUser() .catch(err => { if (err.status == 429) { const retryEpochMs = parseInt(err.headers.get('x-rate-limit-reset'), 10) * 1000; const retryDate = new Date(retryEpochMs); const nowDate = new Date(err.headers.get('date')); const delayMs = retryDate.getTime() - nowDate.getTime() + 1000; // Wait until delayMs has passed before retrying the request } }); ```