DEV Community

Cover image for Access Azure KeyVault Secrets Through Nodejs Application
Dileepa Mabulage
Dileepa Mabulage

Posted on • Updated on

Access Azure KeyVault Secrets Through Nodejs Application

Azure Key Vault is a cloud-based service that allows users to securely store and manage sensitive information, such as passwords, keys, and certificates. This allows for a more secure and efficient way to manage and access sensitive information in a cloud environment.

In this article, we will discuss how to access these secrets through a Node.js application. We will cover how to set up an Azure Key Vault, how to authenticate with it, and how to retrieve and use the secrets in your application. By the end of this article, you will have a better understanding of how to use Azure Key Vault to secure and manage your application's sensitive information.

Table of Contents

  1. Create Nodejs server
  2. Create Azure Key Vault
  3. Add secrets to key Vault
  4. Add secrets from CLI
  5. Register app in Azure Active Directory
  6. Add Access Policies to key Vault
  7. Reveal secrets in Nodejs application

1. Create Nodejs server

  1. Create the directory and run npm init -y in the command prompt
  2. Open that directory in VSCode using typing code . in the command prompt
  3. Open vs code terminal and install the following
npm install express --save 
npm install nodemon --save-dev
Enter fullscreen mode Exit fullscreen mode

Nodemon is a tool that automatically restarts a Node.js application when changes are made to the code. This can save developers time and effort by eliminating the need to manually stop and start the application each time a change is made.

  1. Create an index.js file and paste the following code
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Image description

  1. In your terminal (which should be in the project directory), type nodemon index.js and hit the Enter button.

Image description

  1. Open a new tab in postman or any web browser and the address bar, type http://localhost:3000, and hit the Enter button

Image description

Image description

Now the Node server is up and running...

2. Create Azure key vault

  1. Sign in to the Azure portal at https://portal.azure.com
  2. To set up a Key Vault in Azure:

  3. Open the Azure portal and select "Create a resource" from the menu or Home page.

  4. Search for "Key Vault" and select it from the results.

  5. Click on "Create" in the Key Vault section.

  6. In the "Create key vault" section, enter a unique name for the vault (e.g. "nodejsazurekeyvault") A vault's name must be between 3-24 alphanumeric characters. The name must begin with a letter, end with a letter or digit, and not contain consecutive hyphens, select a subscription and create a new resource group.

  7. Pick a location and keep the other options unchanged.

  8. Click on "Create" to finalize the setup.

Image description

3. Add secrets to key Vault

  1. Click secrets in the left panel
  2. Click Generate/Import at top of the page
  3. Add a secret name, and value
  4. Toggle enables to yes
  5. Click Create

Image description

Image description

4. Add secrets from CLI

  1. Install Azure CLI Download
  2. Run these commands in the PowerShell window
az login
Enter fullscreen mode Exit fullscreen mode
az keyvault secret set --vault-name "<your-unique-keyvault-name>" --name "MultilineSecret" --file "secretfile.txt"
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

5. Register the app in Azure Active Directory

  1. Navigate to Azure Active Directory
  2. Click App registrations on the left panel
  3. Click New Registration
  4. Enter the app name and platform to Web
  5. Register

Image description

Image description

  1. Click certificates and secrets
  2. New client's secret
  3. Add a description and set the expiry date
  4. Add
  5. Copy the value and keep it for future

Image description

Image description

6. Add app to key Vault

  1. Navigate to the Key Vault
  2. Click Access Policies in the left panel

If access policies don't appear. Navigate to access configuration and select vault access policy. And apply.

Image description

  1. Create
  2. Select Secret Management from the template dropdown

Image description

  1. Next
  2. Select keyvaultapp

Image description

  1. Next
  2. Create

7. Reveal secrets in Nodejs application

  1. Go to index.js
  2. Open vs code terminal and install the following
npm install @azure/identity
npm install @azure/keyvault-secrets
npm install dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Create a .ENV file and add the following code
KEYVAULT_URI=<"key vault URL">
AZURE_TENANT_ID=<"registered app in azure active directory">
AZURE_CLIENT_ID=<"registered app in azure active directory">
AZURE_CLIENT_SECRET=<"previously copied value">
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

  1. Add this code to index.js
require("dotenv").config();
const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");
const credential = new DefaultAzureCredential();
const client = new SecretClient(process.env.KEYVAULT_URI, credential);
Enter fullscreen mode Exit fullscreen mode
  1. Create a separate route and add this code (single line secret)
app.get("/secret", (req, res) => {
  client
    .getSecret("testsecret")
    .then((data) => {
      res.send(data.value);
    })
    .catch((error) => {
      console.log(error);
      res.send(error);
    });
});
Enter fullscreen mode Exit fullscreen mode
  1. In your terminal (which should be in the project directory), type nodemon index.js and hit the Enter button.
  2. Open a new tab in postman or any web browser and the address bar, type http://localhost:3000/secret, and hit the Enter button

Image description

Image description

  1. Create a separate route and add this code (multi-line secret)
app.get("/multilinesecret", (req, res) => {
  client
    .getSecret("MultilineSecret")
    .then((data) => {
      const parsedSecret = JSON.parse(data.value);
      res.json(parsedSecret);
    })
    .catch((error) => {
      console.log(error);
      res.send(error);
    });
});
Enter fullscreen mode Exit fullscreen mode
  1. In your terminal (which should be in the project directory), type nodemon index.js and hit the Enter button.

  2. Open a new tab in postman or any web browser and the address bar, type http://localhost:3000/multilinesecret, and hit the Enter button

Image description

Image description

Complete Code

const express = require("express");
const app = express();
const port = 3000;

require("dotenv").config();
const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");
const credential = new DefaultAzureCredential();
const client = new SecretClient(process.env.KEYVAULT_URI, credential);

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.get("/secret", (req, res) => {
  client
    .getSecret("testsecret")
    .then((data) => {
      res.send(data.value);
    })
    .catch((error) => {
      console.log(error);
      res.send(error);
    });
});

app.get("/multilinesecret", (req, res) => {
  client
    .getSecret("MultilineSecret")
    .then((data) => {
      const parsedSecret = JSON.parse(data.value);
      res.json(parsedSecret);
    })
    .catch((error) => {
      console.log(error);
      res.send(error);
    });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Source Code

GitHub

Thank you.

Top comments (2)

Collapse
 
lakincoder profile image
Lakin Mohapatra

Access policiies not showing me under key vault. can you advise ?

Collapse
 
dileepamabulage profile image
Dileepa Mabulage

If access policies don't appear. Navigate to access configuration and select vault access policy. And apply.