Monday, July 13, 2026

OCI IAM: Node.js client example


In a recent customer engagement, the customer requested a Node.js client example that authenticates to the Oracle AI Database via access token by Oracle Cloud Identity & Access Management (OCI IAM) integration. I found the node-oracledb documentation and a previous Node.js example by Sharad Chandran instructive toward this end.

In this Node.js example, I'm connecting to a non-autonomous database using the existing client wallet and existing alias (DEVDB_PDB1_SSL_TOKEN) from the existing tnsnames.ora from blog post on OCI IAM: Token Based Oracle AI Database Authentication.  However, I'm providing the alias to the Node.js script by way of a operating system environment variable named CONNECT_STRING.

First, I have to install Node and oracledb-jdk software.  In my case, I'm running this on a MacOS computer. The easiest way to install these requisites on MacOS is with Homebrew:

brew install -y node oracle-jdk

Then, install the oracledb module along with requisite node modules with the Node Package Manager (npm):

npm install oracledb

In order to open the Oracle client wallet, I had to use the thick JDBC driver by linking the instant client's libclntsh.dylib file into the nodeJS/node_modules/oracledb/build/Release directory.
Note that I linked the file because libclntsh.dylib itself is a link to the a version libclntsh.dylib in the instant client.

ln -s $HOME/.oracle/instant_client/libclntsh.dylib $HOME/.oracle/nodeJS/node_modules/oracledb/build/Release

This sample Node.js script just authenticates to OCI IAM using the access token and executes SQL to return the authenticated user name of the user.

Here is my sample Node.js script:

$ cat ociam_nodejs.js 
const fs = require('fs');
const os = require('os');
const path = require('path');
const oracledb = require('oracledb');

oracledb.initOracleClient()
// Parse out token and private key from token
function getToken() {
  // Set the IAM Token and private key path here
  const tokenPath = path.join(os.homedir(), '/.oci/db-token/token');
  const privateKeyPath = path.join(os.homedir(), '/.oci/db-token/oci_db_key.pem');

  let token = '';
  let privateKey = '';
  try {
    // Read token file
    token = fs.readFileSync(tokenPath, 'utf8');
    // Read private key file
    const privateKeyFileContents = fs.readFileSync(privateKeyPath, 'utf-8');
    privateKeyFileContents.split(/\r?\n/).forEach(line => {
      if (line != '-----BEGIN PRIVATE KEY-----' &&
        line != '-----END PRIVATE KEY-----')
        privateKey = privateKey.concat(line);
    });
  } catch (err) {
    console.error(err);
  } finally {
      const tokenBasedAuthData = {
          token       : token,
          privateKey  : privateKey
      };
      return tokenBasedAuthData;
  }
}

// Determine if the access token needs to be refreshed
let accessTokenStr;

async function tokenCallback(refresh) {
    if (refresh || !accessTokenStr) {
        accessTokenStr = await getToken();
    }
    return accessTokenStr;
}

async function run() {
  // Connec to Oracle AI Database and authenticate with OCI IAM db-token
  const conn = await oracledb.getConnection({
      accessToken    : tokenCallback,             // the callback returns the token object
      externalAuth   : true,                      // must specify external authentication
      connectString  : process.env.CONNECT_STRING // Oracle AI Database connection string
      });

  // Execute SQL: Show authenticated user
  try {
    const result = await conn.execute(`SELECT SYS_CONTEXT ('USERENV','AUTHENTICATED_IDENTITY') FROM DUAL`);
    console.log(result.rows);
  } finally {
    await conn.close();
  }
}

run().catch(console.error);
 

To run the script, I first have to initiate an OCI IAM session with the OCI command line tool.

oci session authenticate --profile-name DBUSER --tenancy-name <oci_tenancy_name> --region <oci_region> --identity-provider-name <oci_identity_domain_name> 
    Please switch to newly opened browser window to log in!
    You can also open the following URL in a web browser window to continue:
https://login.us-phoenix-1.oraclecloud.com/v1/oauth2/authorize?action=login...
Service
    Completed browser authentication process!
Config written to: /Users/dbuser/.oci/config

Next, I request an OCI IAM access token.

oci iam db-token get --profile DBUSER --auth security_token --scope urn:oracle:db::id::<oci_compartment_ocid>::*

Once authenticated and have the access token, then we can run the Node.js script where the alias is set with the CONNECT_STRING string.

export CONNECT_STRING=DEVDB_PDB1_SSL_TOKEN
node ./ociam_nodejs.js 
[ [ '<oci_identity_domain_name>/dbuser@dbauthdemo.com' ] ]

I hope you find this helpful.

Blessings!
















No comments: