Retrieve Hidden Information from Azure Key Vault using Node.js

I'm looking to retrieve the list of users from the Azure active directory. The client has set up a Graph API application but is hesitant to share the client secret, opting instead to use Key Vault for security. How can I access the key required to fetch the user list from my node.js application?

I attempted the code below, but encountered an error and am unsure about the authentication process.

const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");

const credential = new DefaultAzureCredential();

const vaultName = "lsm-keyvault";
const url = `https://${vaultName}.vault.azure.net`;

const client = new SecretClient(url, credential);

const secretName = "Demo";

async function main() {
  const result = await client.setSecret(secretName, "MySecretValue", {
    enabled: false
  });

  console.log(result)
}

Answer №1

If you choose to run the code locally, the DefaultAzureCredential will automatically utilize environmental variables.

In your specific scenario, it is necessary to register an application with Azure AD, obtain the tenant id, client id(i.e. application id),

client secret(i.e. application secret)
, set the environmental variables as AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.

Regarding the 403 error mentioned, if you observe that it was added as a compound entity, chances are the correct service principal associated with the AD App was not added properly to the keyvault's Access policies. The entry should appear as APPLICATION rather than COMPOUND IDENTITY once correctly added.

When adding it, search for either the client Id(i.e. application Id) or

the name of your App Registration
directly to ensure accuracy. Further information on this topic can be found in this similar issue.

To retrieve the secret, simply having the Get permission is sufficient, using the provided code snippet:

const retrievedSecret = await client.getSecret(secretName);

It appears that in your code you are utilizing client.setSecret, which is meant for saving a secret and therefore requires the Set permission to function effectively.

For additional insights, refer to Quickstart: Azure Key Vault client library for Node.js (v4).

Update:

You mentioned the need to eventually deploy this code in a non-Azure environment. To accomplish this, you will have to manually include the required environment variables in your code.

This entails modifying your authentication process by directly inputting the three values into the code.

Replace these lines:

const { DefaultAzureCredential } = require("@azure/identity");
const credential = new DefaultAzureCredential();

With the following:

const { ClientSecretCredential } = require("@azure/identity");
const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);

Refer to - https://www.npmjs.com/package/@azure/identity/v/1.0.3#authenticating-as-a-service-principal

Answer №2

To complete the process, simply follow the steps outlined below:

  • Begin by creating an App in the Azure Active Directory (Service Principal) from the App Registrations section.
  • Next, navigate to the Key Vault resource and access the Access Policy blade. Assign read access to the Azure AD App (Service Principal) created in the previous step.
  • Make sure to set three Environment variables - AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_CLIENT_SECRET within your App Service. Retrieve the values for these variables from the app created in step 1.
  • Utilize DefaultAzureCredential, which is currently in use. This will automatically obtain the credentials from the environment variables specified in the App Service for authentication purposes.

Alternatively, you can dynamically acquire a Key Vault token and utilize that token to access the secrets stored in the Key Vault - https://learn.microsoft.com/en-us/samples/azure-samples/app-service-msi-keyvault-node/app-service-msi-keyvault-node/

For additional information, refer to the following resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resolving Node.js Troubles: An Encounter with 'Module Not Found' Error

After generating a new application, I encountered an error while using the "ionic serve" command. [ng] The specified path cannot be found. [ng] internal/modules/cjs/loader.js:883 [ng] throw err; [ng] ^ [ng] Error: 'C:\Users\shane\Co ...

What discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

Guide to navigating to a different webpage with Node.js

I am a beginner user of NodeJS and I have a specific request. I need assistance with setting up a page redirect from one page to another upon clicking on a link. Any guidance provided will be greatly appreciated. Here is the code snippet: app.js var expr ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

The decision will be dependent on the outcomes provided by the $resource promise

I have been working on calling my API with AngularJS to retrieve a list of 'reports' and then displaying them in a modal or saving the sale depending on whether any results were returned. I've been struggling with this for a while and would ...

What is the best way to implement locking with Mutex in NodeJS?

Accessing external resources (such as available inventories through an API) is restricted to one thread at a time. The challenges I face include: As the NodeJS server processes requests concurrently, multiple requests may attempt to reserve inventories ...

Why does my ajax call always send a GET request instead of a POST?

$.ajax({ type:"post", url: server_url, dataType: "jsonp", jsonpCallback: callback, data:req_json, cache: false, timeout: 60000, success: succeeded, error: got_error }); I've ...

Using two different Readable streams to pipe to the same Writable stream multiple times

In my current project, I am facing the challenge of concatenating a string and a Readable stream. The Readable stream is linked to a file that may contain data in multiple chunks, making it quite large. My objective is to combine these two entities into on ...

The cPanel Node.js application is experiencing difficulties connecting to the MongoDB Atlas cluster, yet it functions without any issues on

Having developed a website using Node.js with MongoDB Atlas as the database, I encountered no issues while testing it on Heroku. However, after purchasing my domain and switching to proper hosting, I faced challenges. I attempted to set up my website by c ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

Ticking mechanism relying on Express JS GET/POST triggers

I'm feeling a bit lost with this issue. I have developed a straightforward app that presents 6 questions to the user. Each question and its corresponding answers are displayed on a dynamically generated view for a specific route dedicated to questions ...

Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to ...

The `findOne` operation in Mongoose fails to complete within the 10000ms time limit

Encountering this error on an intermittent basis can be really frustrating. I am currently using mongoose, express, and typescript to connect to a MongoDB Atlas database. The error message that keeps popping up reads as follows: Operation wallets.findOne() ...

What is the reason for the absence of the $.ajax function in the jQuery package designed for node.js?

Here is my code sample, which I would like to use for practicing with jQuery's ajax function. Note that I have already installed the jQuery package using npm install jquery: var $ = require('jquery'); var remoteValue = false; var doSometh ...

What is the best way to break down multiple query results one after another?

Trying to implement the same destructuring pattern for querying results, but encountering an issue. Take a look at this code snippet: var {rows} = await client.query("SELECT id FROM mytable;"); var Id = rows[0].id; //destructuring works here as expected ...

Make dark mode the default setting in your Next JS application

In my Next JS application, I have implemented both isDarkMode and handleDarkMode functions. Within the Header component, there is a toggle button that allows users to switch between light and dark modes. <ThemeContainer> <label classN ...

Sequelize - The name 'xxx_idx' for the identifier is too lengthy while trying to establish a one-to-many relationship

I am working with 2 tables, physical-assessment-exercise and physical-assessment-lesson. In the file psysical-assessment-lesson.model.js: const Sequelize = require('sequelize'); const DataTypes = Sequelize.DataTypes; module.exports = function ( ...

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

Node.js Token-Based Authorization with Role-Based Access Control

I've searched extensively with no luck. Does anyone know of a method or an npm package that enables users to send a token granting Role-based access control, such as Administrator privileges, on a website? ...

Implementing Singletons in Node.js

While examining some code, I came across the following snippet: var Log = require('log'); // This creates a singleton instance module.exports = new Log('info'); Initially, my reaction was doubting that it could be considered a single ...