|
1 | 1 | ---
|
2 |
| -title: Quickstart - Set and retrieve a secret from Azure Key Vault by using a Node web app | Microsoft Docs |
3 |
| -description: In this quickstart, you set and retrieve a secret from Azure Key Vault by using a Node web app |
4 |
| -services: key-vault |
| 2 | +title: Quickstart - Azure Key Vault client library for Node.js (v4) |
| 3 | +description: Learn how to create, retrieve, and delete secrets from an Azure key vault using the Node.js client library |
5 | 4 | author: msmbaldwin
|
6 |
| -manager: rkarlin |
7 |
| - |
| 5 | +ms.author: mbaldwin |
| 6 | +ms.date: 10/20/2019 |
8 | 7 | ms.service: key-vault
|
9 | 8 | ms.topic: quickstart
|
10 |
| -ms.date: 09/03/2010 |
11 |
| -ms.author: mbaldwin |
12 |
| -ms.custom: mvc |
13 |
| -#Customer intent: As a developer, I want to use Azure Key Vault to store secrets for my app, so that they are kept secure. |
| 9 | + |
14 | 10 | ---
|
15 | 11 |
|
16 |
| -# Quickstart: Set and retrieve a secret from Azure Key Vault by using a Node web app |
| 12 | +# Quickstart: Azure Key Vault client library for Node.js (v4) |
17 | 13 |
|
18 |
| -This quickstart shows you how to store a secret in Azure Key Vault and how to retrieve it by using a web app. Using Key Vault helps keep the information secure. To see the secret value, you would have to run this quickstart on Azure. The quickstart uses Node.js and managed identities for Azure resources. You learn how to: |
| 14 | +Get started with the Azure Key Vault client library for Node.js. Follow the steps below to install the package and try out example code for basic tasks. |
19 | 15 |
|
20 |
| -* Create a key vault. |
21 |
| -* Store a secret in the key vault. |
22 |
| -* Retrieve a secret from the key vault. |
23 |
| -* Create an Azure web application. |
24 |
| -* Enable a [managed identity](../active-directory/managed-service-identity/overview.md) for the web app. |
25 |
| -* Grant the required permissions for the web application to read data from the key vault. |
| 16 | +Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. Use the Key Vault client library for Node.js to: |
26 | 17 |
|
27 |
| -Before you proceed, make sure that you're familiar with the [basic concepts for Key Vault](basic-concepts.md). |
| 18 | +- Increase security and control over keys and passwords. |
| 19 | +- Create and import encryption keys in minutes. |
| 20 | +- Reduce latency with cloud scale and global redundancy. |
| 21 | +- Simplify and automate tasks for SSL/TLS certificates. |
| 22 | +- Use FIPS 140-2 Level 2 validated HSMs. |
28 | 23 |
|
29 |
| -> [!NOTE] |
30 |
| -> Key Vault is a central repository to store secrets programmatically. But to do so, applications and users need to first authenticate to Key Vault--that is, present a secret. In keeping with security best practices, this first secret needs to be rotated periodically. |
31 |
| -> |
32 |
| -> With [managed service identities for Azure resources](../active-directory/managed-identities-azure-resources/overview.md), applications that run in Azure get an identity that Azure manages automatically. This helps solve the *secret introduction problem* so that users and applications can follow best practices and not have to worry about rotating the first secret. |
| 24 | +[API reference documentation](/javascript/api/overview/azure/key-vault?view=azure-node-latest) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/keyvault) | [Package (npm)](https://www.npmjs.com/package/@azure/keyvault-secrets) |
33 | 25 |
|
34 | 26 | ## Prerequisites
|
35 | 27 |
|
36 |
| -* [Node.js](https://nodejs.org/en/) |
37 |
| -* [Git](https://www.git-scm.com/) |
38 |
| -* [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli?view=azure-cli-latest) 2.0.4 or later. This quickstart requires that you run the Azure CLI locally. Run `az --version` to find the version. If you need to install or upgrade the CLI, see [Install Azure CLI 2.0](https://review.docs.microsoft.com/en-us/cli/azure/install-azure-cli?branch=master&view=azure-cli-latest). |
39 |
| -* An Azure subscription. If you don't have an Azure subscription, create a [free account](https://azure.microsoft.com/free/?WT.mc_id=A261C142F) before you begin. |
| 28 | +- An Azure subscription - [create one for free](https://azure.microsoft.com/free/?WT.mc_id=A261C142F). |
| 29 | +- Current [Node.js](https://nodejs.org) for your operating system. |
| 30 | +- [Azure CLI](/cli/azure/install-azure-cli?view=azure-cli-latest) or [Azure PowerShell](/powershell/azure/overview) |
| 31 | + |
| 32 | +This quickstart assumes you are running [Azure CLI](/cli/azure/install-azure-cli?view=azure-cli-latest) in a Linux terminal window. |
| 33 | + |
| 34 | +## Setting up |
| 35 | + |
| 36 | +### Install the package |
| 37 | + |
| 38 | +From the console window, install the Azure Key Vault secrets library for Node.js. |
| 39 | + |
| 40 | +```console |
| 41 | +npm install @azure/keyvault-secrets |
| 42 | +``` |
| 43 | + |
| 44 | +For this quickstart, you will need to install the azure.identity package as well: |
| 45 | + |
| 46 | +```console |
| 47 | +npm install @azure/identity |
| 48 | +``` |
| 49 | + |
| 50 | +### Create a resource group and key vault |
40 | 51 |
|
41 |
| -## Log in to Azure |
| 52 | +This quickstart uses a pre-created Azure key vault. You can create a key vault by following the steps in the [Azure CLI quickstart](quick-create-cli.md), [Azure PowerShell quickstart](quick-create-powershell.md), or [Azure portal quickstart](quick-create-portal.md). Alternatively, you can simply run the Azure CLI commands below. |
42 | 53 |
|
43 |
| -To log in to Azure by using the Azure CLI, enter: |
| 54 | +> [!Important] |
| 55 | +> Each key vault must have a unique name. Replace <your-unique-keyvault-name> with the name of your key vault in the following examples. |
44 | 56 |
|
45 | 57 | ```azurecli
|
46 |
| -az login |
| 58 | +az group create --name "myResourceGroup" -l "EastUS" |
| 59 | +
|
| 60 | +az keyvault create --name <your-unique-keyvault-name> -g "myResourceGroup" |
47 | 61 | ```
|
48 | 62 |
|
49 |
| -## Create a resource group |
| 63 | +### Create a service principal |
50 | 64 |
|
51 |
| -Create a resource group by using the [az group create](/cli/azure/group#az-group-create) command. An Azure resource group is a logical container into which Azure resources are deployed and managed. |
| 65 | +The simplest way to authenticate an cloud-based application is with a managed identity; see [Use an App Service managed identity to access Azure Key Vault](managed-identity.md) for details. For the sake of simplicity however, this quickstarts creates a console application. Authenticating a desktop application with Azure requires the use of a service principal and an access control policy. |
52 | 66 |
|
53 |
| -Select a resource group name and fill in the placeholder. |
54 |
| -The following example creates a resource group in the East US location. |
| 67 | +Create a service principle using the Azure CLI [az ad sp create-for-rbac](/cli/azure/ad/sp?view=azure-cli-latest#az-ad-sp-create-for-rbac) command: |
55 | 68 |
|
56 | 69 | ```azurecli
|
57 |
| -# To list locations: az account list-locations --output table |
58 |
| -az group create --name "<YourResourceGroupName>" --location "East US" |
| 70 | +az ad sp create-for-rbac -n "http://mySP" --sdk-auth |
59 | 71 | ```
|
60 | 72 |
|
61 |
| -The resource group that you just created is used throughout this article. |
| 73 | +This operation will return a series of key / value pairs. |
| 74 | + |
| 75 | +```azurecli |
| 76 | +{ |
| 77 | + "clientId": "7da18cae-779c-41fc-992e-0527854c6583", |
| 78 | + "clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002", |
| 79 | + "subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3", |
| 80 | + "tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77", |
| 81 | + "activeDirectoryEndpointUrl": "https://login.microsoftonline.com", |
| 82 | + "resourceManagerEndpointUrl": "https://management.azure.com/", |
| 83 | + "activeDirectoryGraphResourceId": "https://graph.windows.net/", |
| 84 | + "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", |
| 85 | + "galleryEndpointUrl": "https://gallery.azure.com/", |
| 86 | + "managementEndpointUrl": "https://management.core.windows.net/" |
| 87 | +} |
| 88 | +``` |
62 | 89 |
|
63 |
| -## Create a key vault |
| 90 | +Take note of the clientId and clientSecret, as we will use them in the [Set environmental variable](#set-environmental-variables) step below. |
64 | 91 |
|
65 |
| -Next you create a key vault by using the resource group that you created in the previous step. Although this article uses “ContosoKeyVault” as the name, you have to use a unique name. Provide the following information: |
| 92 | +#### Give the service principal access to your key vault |
66 | 93 |
|
67 |
| -* Key vault name. |
68 |
| -* Resource group name. The name must be a string of 3-24 characters and must contain only 0-9, a-z, A-Z, and a hyphen (-). |
69 |
| -* Location: **East US**. |
| 94 | +Create an access policy for your key vault that grants permission to your service principal by passing the clientId to the [az keyvault set-policy](/cli/azure/keyvault?view=azure-cli-latest#az-keyvault-set-policy) command. Give the service principal get, list, and set permissions for both keys and secrets. |
70 | 95 |
|
71 | 96 | ```azurecli
|
72 |
| -az keyvault create --name "<YourKeyVaultName>" --resource-group "<YourResourceGroupName>" --location "East US" |
| 97 | +az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --secret-permissions delete get list set --key-permissions create decrypt delete encrypt get list unwrapKey wrapKey |
73 | 98 | ```
|
74 | 99 |
|
75 |
| -At this point, your Azure account is the only one that's authorized to perform any operations on this new vault. |
| 100 | +#### Set environmental variables |
76 | 101 |
|
77 |
| -## Add a secret to the key vault |
| 102 | +The DefaultAzureCredential method in our application relies on three environmental variables: `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_TENANT_ID`. Set these variables to the clientId, clientSecret, and tenantId values you noted in the [Create a service principal](#create-a-service-principal) step using the `export VARNAME=VALUE` format. (This only sets the variables for your current shell and processes created from the shell; to permanently add these variables to your environment, edit your `/etc/environment ` file.) |
78 | 103 |
|
79 |
| -We're adding a secret to help illustrate how this works. You might be storing a SQL connection string or any other information that you need to keep securely but make available to your application. In this tutorial, the password will be called **AppSecret** and will store the value of **MySecret** in it. |
| 104 | +You will also need to save your key vault name as an environment variable called `KEY_VAULT_NAME`. |
80 | 105 |
|
81 |
| -Type the following commands to create a secret in the key vault called **AppSecret**. This secret will store the value **MySecret**. |
| 106 | +```console |
| 107 | +export AZURE_CLIENT_ID=<your-clientID> |
82 | 108 |
|
83 |
| -```azurecli |
84 |
| -az keyvault secret set --vault-name "<YourKeyVaultName>" --name "AppSecret" --value "MySecret" |
| 109 | +export AZURE_CLIENT_SECRET=<your-clientSecret> |
| 110 | + |
| 111 | +export AZURE_TENANT_ID=<your-tenantId> |
| 112 | + |
| 113 | +export KEY_VAULT_NAME=<your-key-vault-name> |
| 114 | +```` |
| 115 | + |
| 116 | +## Object model |
| 117 | + |
| 118 | +The Azure Key Vault client library for Node.js allows you to manage keys and related assets such as certificates and secrets. The code samples below will show you how to create a client, set a secret, retrieve a secret, and delete a secret. |
| 119 | + |
| 120 | +The entire console app is available at https://github.com/Azure-Samples/key-vault-dotnet-core-quickstart/tree/master/key-vault-console-app. |
| 121 | + |
| 122 | +## Code examples |
| 123 | + |
| 124 | +### Add directives |
| 125 | + |
| 126 | +Add the following directives to the top of your code: |
| 127 | + |
| 128 | +```javascript |
| 129 | +const { DefaultAzureCredential } = require("@azure/identity"); |
| 130 | +const { SecretClient } = require("@azure/keyvault-secrets"); |
| 131 | +``` |
| 132 | + |
| 133 | +### Authenticate and create a client |
| 134 | + |
| 135 | +Authenticating to your key vault and creating a key vault client depends on the environmental variables from the [Set environmental variables](#set-environmental-variables) step above, and the [SecretClient constructor](/javascript/api/@azure/keyvault-secrets/secretclient?view=azure-node-latest#secretclient-string--tokencredential--pipelineoptions-). |
| 136 | + |
| 137 | +The name of your key vault is expanded to the key vault URI, in the format `https://<your-key-vault-name>.vault.azure.net`. |
| 138 | + |
| 139 | +```javascript |
| 140 | +const keyVaultName = process.env["KEY_VAULT_NAME"]; |
| 141 | +const KVUri = "https://" + keyVaultName + ".vault.azure.net"; |
| 142 | + |
| 143 | +const credential = new DefaultAzureCredential(); |
| 144 | +const client = new SecretClient(KVUri, credential); |
85 | 145 | ```
|
86 | 146 |
|
87 |
| -To view the value contained in the secret as plain text: |
| 147 | +### Save a secret |
| 148 | + |
| 149 | +Now that your application is authenticated, you can put a secret into your keyvault using the [client.setSecret method](/javascript/api/@azure/keyvault-secrets/secretclient?view=azure-node-latest#setsecret-string--string--setsecretoptions-) This requires a name for the secret -- we're using "mySecret" in this sample. |
| 150 | + |
| 151 | +```javascript |
| 152 | +await client.setSecret(secretName, secretValue); |
| 153 | +``` |
| 154 | + |
| 155 | +You can verify that the secret has been set with the [az keyvault secret show](/cli/azure/keyvault/secret?view=azure-cli-latest#az-keyvault-secret-show) command: |
88 | 156 |
|
89 | 157 | ```azurecli
|
90 |
| -az keyvault secret show --name "AppSecret" --vault-name "<YourKeyVaultName>" |
| 158 | +az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret |
91 | 159 | ```
|
92 | 160 |
|
93 |
| -This command shows the secret information, including the URI. After you complete these steps, you should have a URI to a secret in a key vault. Make note of this information. You'll need it in a later step. |
| 161 | +### Retrieve a secret |
| 162 | + |
| 163 | +You can now retrieve the previously set value with the [client.getSecret method](/javascript/api/@azure/keyvault-secrets/secretclient?view=azure-node-latest#getsecret-string--getsecretoptions-). |
| 164 | + |
| 165 | +```javascript |
| 166 | +const retrievedSecret = await client.getSecret(secretName); |
| 167 | + ``` |
94 | 168 |
|
95 |
| -## Clone the repo |
| 169 | +Your secret is now saved as `retrievedSecret.value`. |
96 | 170 |
|
97 |
| -Clone the repo to make a local copy where you can edit the source. Run the following command: |
| 171 | +### Delete a secret |
98 | 172 |
|
| 173 | +Finally, let's delete the secret from your key vault with the [client.beginDeleteSecret method](/javascript/api/@azure/keyvault-secrets/secretclient?view=azure-node-latest#begindeletesecret-string--begindeletesecretoptions-). |
| 174 | + |
| 175 | +```javascript |
| 176 | +await client.beginDeleteSecret(secretName) |
99 | 177 | ```
|
100 |
| -git clone https://github.com/Azure-Samples/key-vault-node-quickstart.git |
| 178 | + |
| 179 | +You can verify that the secret is gone with the [az keyvault secret show](/cli/azure/keyvault/secret?view=azure-cli-latest#az-keyvault-secret-show) command: |
| 180 | + |
| 181 | +```azurecli |
| 182 | +az keyvault secret show --vault-name <your-unique-keyvault-name> --name mySecret |
101 | 183 | ```
|
102 | 184 |
|
103 |
| -## Install dependencies |
| 185 | +## Clean up resources |
104 | 186 |
|
105 |
| -Run the following commands to install dependencies: |
| 187 | +When no longer needed, you can use the Azure CLI or Azure PowerShell to remove your key vault and the corresponding resource group. |
106 | 188 |
|
| 189 | +```azurecli |
| 190 | +az group delete -g "myResourceGroup" -l "EastUS" |
107 | 191 | ```
|
108 |
| -cd key-vault-node-quickstart |
109 |
| -npm install |
| 192 | + |
| 193 | +```azurepowershell |
| 194 | +Remove-AzResourceGroup -Name "myResourceGroup" |
110 | 195 | ```
|
111 | 196 |
|
112 |
| -This project uses two Node modules: [ms-rest-azure](https://www.npmjs.com/package/ms-rest-azure) and [azure-keyvault](https://www.npmjs.com/package/azure-keyvault). |
| 197 | +## Sample code |
113 | 198 |
|
114 |
| -## Publish the web app to Azure |
| 199 | +```javascript |
| 200 | +const { DefaultAzureCredential } = require("@azure/identity"); |
| 201 | +const { SecretClient } = require("@azure/keyvault-secrets"); |
115 | 202 |
|
116 |
| -Create an [Azure App Service](https://azure.microsoft.com/services/app-service/) plan. You can store multiple web apps in this plan. |
| 203 | +const readline = require('readline'); |
117 | 204 |
|
118 |
| - ``` |
119 |
| - az appservice plan create --name myAppServicePlan --resource-group myResourceGroup |
120 |
| - ``` |
121 |
| -Next, create a web app. In the following example, replace `<app_name>` with a globally unique app name (valid characters are a-z, 0-9, and -). The runtime is set to NODE|6.9. To see all supported runtimes, run `az webapp list-runtimes`. |
| 205 | +function askQuestion(query) { |
| 206 | + const rl = readline.createInterface({ |
| 207 | + input: process.stdin, |
| 208 | + output: process.stdout, |
| 209 | + }); |
122 | 210 |
|
123 |
| - ``` |
124 |
| - # Bash |
125 |
| - az webapp create --resource-group myResourceGroup --plan myAppServicePlan --name <app_name> --runtime "NODE|6.9" --deployment-local-git |
126 |
| - ``` |
127 |
| -When the web app has been created, the Azure CLI shows output similar to the following example: |
| 211 | + return new Promise(resolve => rl.question(query, ans => { |
| 212 | + rl.close(); |
| 213 | + resolve(ans); |
| 214 | + })) |
| 215 | +} |
128 | 216 |
|
129 |
| - ``` |
130 |
| - { |
131 |
| - "availabilityState": "Normal", |
132 |
| - "clientAffinityEnabled": true, |
133 |
| - "clientCertEnabled": false, |
134 |
| - "cloningInfo": null, |
135 |
| - "containerSize": 0, |
136 |
| - "dailyMemoryTimeQuota": 0, |
137 |
| - "defaultHostName": "<app_name>.azurewebsites.net", |
138 |
| - "enabled": true, |
139 |
| - "deploymentLocalGitUrl": "https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git" |
140 |
| - < JSON data removed for brevity. > |
141 |
| - } |
142 |
| - ``` |
143 |
| -Browse to your newly created web app, and you should see that it's functioning. Replace `<app_name>` with a unique app name. |
| 217 | +async function main() { |
144 | 218 |
|
145 |
| - ``` |
146 |
| - http://<app name>.azurewebsites.net |
147 |
| - ``` |
148 |
| -The preceding command also creates a Git-enabled app that enables you to deploy to Azure from your local Git repository. The local Git repo is configured with this URL: `https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git`. |
| 219 | + const keyVaultName = process.env["KEY_VAULT_NAME"]; |
| 220 | + const KVUri = "https://" + keyVaultName + ".vault.azure.net"; |
149 | 221 |
|
150 |
| -After you finish the preceding command, you can add an Azure remote to your local Git repository. Replace `<url>` with the URL of the Git repo. |
| 222 | + const credential = new DefaultAzureCredential(); |
| 223 | + const client = new SecretClient(KVUri, credential); |
151 | 224 |
|
152 |
| - ``` |
153 |
| - git remote add azure <url> |
154 |
| - ``` |
| 225 | + const secretName = "mySecret"; |
| 226 | + var secretValue = await askQuestion("Input the value of your secret > "); |
155 | 227 |
|
156 |
| -## Enable a managed identity for the web app |
| 228 | + console.log("Creating a secret in " + keyVaultName + " called '" + secretName + "' with the value '" + secretValue + "` ..."); |
| 229 | + await client.setSecret(secretName, secretValue); |
157 | 230 |
|
158 |
| -Azure Key Vault provides a way to securely store credentials and other keys and secrets, but your code needs to authenticate to Key Vault to retrieve them. [Managed identities for Azure resources overview](../active-directory/managed-identities-azure-resources/overview.md) makes solving this problem simpler, by giving Azure services an automatically managed identity in Azure Active Directory (Azure AD). You can use this identity to authenticate to any service that supports Azure AD authentication, including Key Vault, without having any credentials in your code. |
| 231 | + console.log("Done."); |
159 | 232 |
|
160 |
| -Run the assign-identity command to create the identity for this application: |
| 233 | + console.log("Forgetting your secret."); |
| 234 | + secretValue = ""; |
| 235 | + console.log("Your secret is '" + secretValue + "'."); |
161 | 236 |
|
162 |
| -```azurecli |
163 |
| -az webapp identity assign --name <app_name> --resource-group "<YourResourceGroupName>" |
164 |
| -``` |
| 237 | + console.log("Retrieving your secret from " + keyVaultName + "."); |
165 | 238 |
|
166 |
| -This command is the equivalent of going to the portal and switching the **Identity / System assigned** setting to **On** in the web application properties. |
| 239 | + const retrievedSecret = await client.getSecret(secretName); |
167 | 240 |
|
168 |
| -### Assign permissions to your application to read secrets from Key Vault |
| 241 | + console.log("Your secret is '" + retrievedSecret.value + "'."); |
| 242 | + console.log("Deleting your secret from " + keyVaultName + " ..."); |
169 | 243 |
|
170 |
| -Make note of the output of the previous command. It should be in the format: |
171 |
| - |
172 |
| - { |
173 |
| - "principalId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", |
174 |
| - "tenantId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", |
175 |
| - "type": "SystemAssigned" |
176 |
| - } |
177 |
| - |
178 |
| -Then, run the following command by using the name of your key vault and the value of **principalId**: |
| 244 | + await client.beginDeleteSecret(secretName); |
179 | 245 |
|
180 |
| -```azurecli |
181 |
| -az keyvault set-policy --name '<YourKeyVaultName>' --object-id <PrincipalId> --secret-permissions get set |
182 |
| -``` |
| 246 | + console.log("Done."); |
183 | 247 |
|
184 |
| -## Deploy the Node app to Azure and retrieve the secret value |
| 248 | +} |
185 | 249 |
|
186 |
| -Run the following command to deploy the app to Azure: |
| 250 | +main() |
187 | 251 |
|
188 | 252 | ```
|
189 |
| -git push azure master |
190 |
| -``` |
191 |
| - |
192 |
| -After this, when you browse to `https://<app_name>.azurewebsites.net`, you can see the secret value. Make sure that you replaced the name `<YourKeyVaultName>` with your vault name. |
193 | 253 |
|
194 | 254 | ## Next steps
|
195 | 255 |
|
196 |
| -In this quickstart you created a Key Vault and stored a secret in it. To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below. |
| 256 | +In this quickstart you created a key vault, stored a secret, and retrieved that secret. |
| 257 | + |
| 258 | +To learn more about Key Vault and how to integrate it with your applications, continue on to the articles below. |
197 | 259 |
|
198 | 260 | - Read an [Overview of Azure Key Vault](key-vault-overview.md)
|
199 | 261 | - See the [Azure Key Vault developer's guide](key-vault-developers-guide.md)
|
|
0 commit comments