Search code examples
azureazure-functionsazure-keyvaultazure-function-appazure-node-sdk

How to extract Secret key from Azure key vault in Azure Function App on Nodejs stack


I have created an Azure Function app in Nodejs version 12. My hosting environment is windows. What is the easiest way to capture the username and password which are saved in Azure key vault inside my function. Also I am using Inline code Editor so how should be capture the credentials in code.

Thanks


Solution

  • The node SDK used in above answer is going to be deprecated and won't have new feature and releases. Instead, the new versions are released here:

    https://www.npmjs.com/package/@azure/keyvault-secrets

    Here are the detailed steps to retrieve the secret value for your reference.

    1.Enable system assigned managed identity in your function.

    enter image description here

    2.Add this service principal to the access policy of your key vault.

    enter image description here

    3.Install the dependencies to your function.

      "dependencies": {
        "@azure/identity": "^1.0.3",
        "@azure/keyvault-secrets": "^4.0.4"
      }
    

    4.Here is my testing function code

    module.exports = async function (context, req) {
    
    const { DefaultAzureCredential } = require("@azure/identity");
    const { SecretClient } = require("@azure/keyvault-secrets");
    const keyVaultName = "tonykeyvault20190801";
    const KVUri = "https://" + keyVaultName + ".vault.azure.net";
    
    const credential = new DefaultAzureCredential();
    const client = new SecretClient(KVUri, credential);
    
    const retrievedSecret = await client.getSecret("username");
    const username=retrievedSecret.value;
    context.log(username);
      context.res = {
          body: username 
      };
    }
    

    5.The execution result.

    enter image description here