Authenticating End-users with Node.js and Oracle Identity Cloud Service

By August 2, 2019 Uncategorized

I once wrote about authenticating users using database tables and JWTs. While functional, custom solutions like that put the onus on you to protect the user’s credentials and they’re a far cry from a full-blown platform for security and identity. Oracle’s solution for such a platform is called Oracle Identity Cloud Service (IDCS). In this tutorial, I’ll show you how to authenticate end-users using OpenID Connect 1.0 with IDCS and protect your Node.js based APIs.



From the OpenID Connect 1.0 spec’s abstract:

OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It enables Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.

To demonstrate how to add IDCS based authentication to a Node.js app, I’ll pick up the code where the series on creating a REST API left off. If you wish to follow along in this tutorial, I recommend that you clone the oracle-db-examples repo from GitHub and start with the files in javascript/rest-api/part-5-manual-pagination-sorting-and-filtering/hr_app. To run this application before making any changes, you will need to run npm install, set the environment variables referenced in config/database.js, and then run node .. See that series for more information if needed.

To access a completed version of this tutorial, see the javascript/idcs-authentication directory of the oracle-db-examples repo.

The IDCS team provides many SDKs, including a Node.js module, to integrate with various platforms. The Node.js module includes a Passport strategy, so I’ll bring in Passport for authentication with Express. Finally, to avoid sending any potentially sensitive information to the client, I’ll use the express-session module combined with Passport’s session support for cookie-based sessions.

The front-end demo app is implemented using Bootstrap and vanilla JavaScript. This should make it easy enough to follow the logic and later integrate the concepts into your front-end JavaScript framework of choice.

You will need an Oracle Cloud account to work with IDCS and complete this tutorial. If you don’t already have an account, you can request a free trial account at

Register demo app with IDCS

To allow an app to authenticate users, you need to register it with IDCS first. Follow these steps to register the Node.js demo app with IDCS.

  • Log in to your Oracle Cloud account.
  • Click the Navigation Drawer icon in the upper left-hand corner and select Identity > Federation.
  • In the Federation page, click the Oracle Identity Cloud Service Console link.
  • In the Identity Console page, click the Navigation Drawer icon and select Applications.
  • In the Applications page, click the Add button.
  • In the Add Application dialog, select the Confidential Application option. This will take you to the Add Confidential Application wizard.
  • In the Details pane, set Name to Node.js Demo App, then click Next >.
  • In the Client pane, select Configure this application as a client now and populate the fields as follows.
    • Allowed Grant Types: Select Client Credentials and Authorization Code.
    • Allow non-HTTPS URLs: Select this option.
    • Redirect URL: http://localhost:3000/callback
    • Post Logout Redirect URL: http://localhost:3000
  • While still in the Client pane, click the Add button under Grant the client access to Identity Cloud Service Admin APIs.
  • In the Add App Role dialog, select Authenticator Client and Me, then click the Add button.
  • Click Next in the Client pane and in the following panes until you reach the last pane. Then click Finish.
  • Make a note of the Client ID and Client Secret values displayed in the Application Added dialog. The Node.js application will need these values to work with IDCS. Click Close when finished.
  • In the Node.js Demo App page, click the Activate button.
  • In the Active Application? dialog, click the Activate Application button.

At this point, the Node.js app is registered with IDCS and you’re ready to start building out the app to authenticate users.

Before leaving the Identity Console, go ahead and download the Node.js SDK. Start by clicking the Navigation Drawer icon and then select Settings > Downloads. Locate the Node.js SDK from the list and click the download button. This will download a zip file to your machine that you’ll use in Part 2.

Configure the demo app to work with IDCS

As mentioned in the overview, I’ll start enhancing the Node.js app where the REST series left off. If you’ve not done so already, you can clone the oracle-db-examples repo and change directories to the last part of that series with the following commands:

Create a new configuration file named authentication.js in the config directory. Copy and paste the following code into the file and save your changes.


  • Lines 1-27: The authentication configuration module exports an object with two main properties: idcs (for IDCS specific values) and sessionOpts (for the express-session module).
    • Lines 3-11: The classOpts property is used to instantiate two classes in the IDCS SDK for Node.js: OIDCStrategy and IdcsAuthenticationManager. You’ll see how these are used later on.
    • Lines 12-17: The rest of the IDCS related configuration attributes will be used in various parts of the authentication module you’ll create in the next part of this tutorial.
    • Lines 19-26: The express-session configuration attributes are documented here. I’ve set the session cookie to expire after 8 hours, which matches the default IDCS session expiration (found under Settings > Session Settings).

There are three environment variables used in the configuration file: IDCS_CLIENT_TENANT, IDCS_CLIENT_ID, IDCS_CLIENT_SECRET. These environment variables need to be set before running the Node.js application.

The IDCS_CLIENT_ID and IDCS_CLIENT_SECRET values were provided when registering the application with IDCS. The IDCS_CLIENT_TENANT value can be obtained from the Identity Console by clicking on your user icon and selecting About.

A dialog with IDCS details specific to your instance will be displayed. The Instance GUID, which starts with “idcs-” followed by a 32 character GUID, is the value needed for the IDCS_CLIENT_TENANT environment variable.

Modify the following commands to have the correct values and then run them in the terminal to set the environment variables:

Note that there are additional environment variables in the config/database.js file that will need to be set to connect to the database.

With the configuration file added and environment variables set, the next step is to get the dependencies installed. Open a terminal in the application’s top-level hr_app directory. Run the following command to install the existing dependencies in the package.json file and add two new ones.

Next, locate the IDCS SDK zip file that you downloaded previously and extract the contents (don’t just open, extract). Inside you’ll find two directories: docs and passport-idcs. Copy the entire passport-idcs directory to the hr_app/node_modules directory of the application.

Note that subsequent npm commands may remove the passport-idcs directory from the node_modules directory. If this happens, simply copy the directory over again. The IDCS team is working on publishing the module as a standard npm module but this is the process for now.

The application is now configured to work with IDCS. It’s time to start building out the authentication logic.

Start a new authentication module

In this part, you will create an authentication module that will encapsulate all of the logic related to authentication. Create a new authentication.js file in the services directory. Copy and paste the following code into the file.


  • Lines 1-6: Several external dependencies are required in. The IdcsAuthenticationManager class is used to create a new instance named authMgr. This class contains all of the methods needed to handle authentication with IDCS and will be used in later parts of this tutorial.
  • Lines 8-29: A function named initWebServer is declared and exported from the module. The web server module will invoke this method passing along the express application. This allows all of the app’s authentication related logic to reside in the authentication module.
    • Line 9: Express-session is added to the app via app.use.
    • Lines 11-17: Basic functions are defined for Passport’s serializeUser and deserializeUser methods. You can learn more about these functions in the Configure section of the Passport doc.
    • Lines 19-21: The passport.use method is used to register the IDCS strategy with Passport.
    • Lines 23-24: Passport’s initialize and session middleware are added to the express application.
    • Line 26: A route handler for /user is added to the web server. This endpoint will be used by the front end app to verify that the user is authenticated.
  • Lines 31-38: The user function uses the isAuthenticated function that Passport adds to the request object to verify that the user is authenticated. If so, the user’s details are obtained from the user property of the request and sent back. Otherwise, an object that indicates the user is not authenticated is sent.

Now that the authentication module is in place, the next step is to call its initWebServer function from the web server module. Open the web-server.js file in the services directory. Add the following line toward the top of the file, under the line that requires in the router module.

Add the following lines to the initialize function, under the lines that add the express.json middleware to the app.

With the authentication module in place, you can create the front-end demo application.

Create the front-end demo app

The front-end demo app is made up of just two files. Start by creating a directory named www under the hr_app directory. Within the www directory, create a new file named index.html. Copy the following code to the file and save your changes.


  • Lines 14-20: Two buttons are added to the page, one to log in and another to log out. These are form buttons that will issue GET requests to the endpoints specified in the action attribute. Handlers for those endpoints will be added to the web server later on.
  • Lines 35-48: A table to display employee data is added to the page. The data will be fetched from the /api/employees endpoint, which will need to be locked down later on.
  • Line 56: The main JavaScript file for the application is brought in. You will create this file in the next step.

Create another file named idcs-authentication-demo.js in the www directory. Add the following code to the file and save your changes.


  • Lines 3: jQuery’s ready event is used to invoke the init function when the DOM tree is loaded.
  • Lines 5-17: The init function is defined. Within it, the fetch API is used to issue a GET request on the /user endpoint. If the end-user is authenticated, then the handleAuthenticated function is invoked. Otherwise, handleUnauthenticated is invoked.
  • Lines 19-44: The handleAuthenticated function is defined. This function displays the logout button and then uses the fetch API to issue a GET request on the /api/employees endpoint. Because the end-user was verified as authenticated, the request should succeed, and the employee data returned is injected into the DOM.
  • Lines 46-49: The handleUnauthenticated function is defined. This function displays the login button and a message indicating that the user is not logged in. The message includes a link to help test whether or not the actual API endpoint is locked down.

Now that the front-end application files are in place, the webserver needs to be updated to serve them. Return to the services/web-server.js file and add the following lines to the initialize function, under the lines that add the express.json middleware to the app.

Okay, it’s time to run the first test! Return to the terminal where hr_app is the working directory and the environment variables for the application have been set. Run node . to start the application. When you see the “Web server listening on localhost:3000” message, open a browser and navigate to localhost:3000. You should see the following.

Currently, if you click the Log In button, you’ll get an error because that route has not yet been defined in the Node.js app. Also, although it looks as though the employee data is safe because it’s not displayed, that is not the case. If you click the Click here link above the Employees table, you’ll see that the API route isn’t protected, it just wasn’t called.

In the steps that follow, you’ll add the authentication logic and lock down the API endpoints.

Add logic to log in

In this part, you’ll add the ability for end-users to authenticate with IDCS. Return to the services/authentication.js file and add the following lines of code to the initWebServer function, just below the line that adds the route handler for /user.


  • Line 3: As you’ve already seen, the /login route is used when the user clicks the Log In button in the front-end app. This route will invoke the login middleware function, which is described below.
  • Lines 5-15: The /callback route uses three middleware functions to complete the authentication process in Node.js after the user has successfully authenticated with IDCS. First the callback function (described below) is invoked, then Passport’s authenticate middleware is used to authenticate the user using the IDCS strategy, and finally, an anonymous middleware function redirects the user to their original target page or the home page.

Copy and paste the following functions to the end of the services/authentication.js file, after the user function definition. Don’t forget to save your changes.


  • Lines 3-16: The login function is an Express middleware function that uses the authMgr instance to obtain the IDCS URL that the end-user is then redirected to for authentication. Upon successful authentication, IDCS will redirect the user’s browser to the callback route passing along the authZcode in the query string of the redirect header.
  • Lines 18-33: The callback function obtains the authZcode from IDCS from the query string of the request object and uses it to get an id_token and an access_token (learn more about these tokens here). A header is then added to the request object before next is invoked, which forwards the request to the passport.authenticate middleware.

Restart the Node.js application and navigate to the front-end application again. If you click the Log In button, you should be redirected to the IDCS authentication page. If you were logged into your cloud account from before you may skip this step. Either log out or use a different browser.

After successfully authenticating, you should be redirected back to the application where you’ll see the Log Out button and the employee data in the table.

Now that you can log in, all that’s left to do is add the ability to log out and lock down the API endpoints.

Add logic to log out

Return to the services/authentication.js file and add the following line of code to the end of the initWebServer function, just below the lines that add the route handler for the /callback route.

Next, add the following code to the end of the services/authentication.js file, after the callback function definition.


  • Line 5: The logout function first obtains the correct logout URL for IDCS and stores that in the logoutUrl variable.
  • Line 7: The logout method that Passport adds to the request object is invoked which logs the user out of Passport.
  • Lines 9-16: The destroy method of the session instance is invoked to ensure that all information in the session is removed. Once complete, the user is redirected to the IDCS logout URL to log the user out there. When finished, IDCS will redirect the user to the Post Logout Redirect URL that was specified earlier.

Restart the Node.js application and ensure that the logout functionality is working as designed. Because express-session saves sessions in memory by default, you will need to log in again after restarting NOde.js before you can log out successfully.

Note that even after logging out, if you click the Click here link above the employees table you can still see employee data. You will lock down that endpoint in the last step.

Protect API endpoints

The last step, locking down the API endpoints, is arguably the most crucial step of all! If API endpoints aren’t locked down, then authentication doesn’t really mean much. Return to the services/authentication.js file and add the following lines of code to the end of the file, just below the lines that define the logout function.


  • Line 4: The ensureAuthenticated function returns an Express middleware function that can be used to secure API endpoints.
  • Line 5: The isAuthenticated function that Passport adds to the request object is used to verify that the user is authenticated.
  • Lines 8-16: If a group parameter was passed to ensureAuthenticated, then in addition to ensuring the user is authenticated, the middleware will ensure the user belongs to the specified group.
  • Lines 20-22: If the user is not authenticated, then their destination page is saved to their session and they are redirected to login.

Open the services/router.js file and add the following line toward the top of the file, just after the line that requires in the router module.

Next, replace the existing /employees route definition (all five lines) with the following code.

The all method of the router is used to add the ensureAuthenticated middleware. Note that ensureAuthenticated is invoked, not merely referenced. Router middleware functions are executed in the order that they’re added, so all will verify that the user is authenticated before passing control to any subsequent handlers.

Depending on your requirements, you can add the ensureAuthenticated middleware in different places, such as in front of individual controller functions. This would allow some HTTP methods to be protected while others are not.

Save all of your changes and restart the Node.js application. If you are not logged in, you should no longer be able to access any employee information (even using the Click here link). You can optionally test passing a group name to the ensureAuthenticated function for a basic authorization check. Just be sure to create and add the user to the group in IDCS.

Controller logic that is executed after ensureAuthenticated will have access to the authenticated user’s information via request.user. This information can be useful for end-to-end tracing, auditing, and other security related features of Oracle Database, such as VPD. See this section of the node-oracledb documentation to learn more.