How to access Key Vault with Azure Managed Service Identity in node?

怎甘沉沦 提交于 2019-12-06 05:19:16

Using the loginWithAppServiceMSI() method from ms-rest-azure will autodetect if you're on a WebApp and get the token from the MSI endpoint. Then, the code is simply:

function getKeyVaultCredentials(){
    return msRestAzure.loginWithAppServiceMSI({resource: 'https://vault.azure.net'});
}

function getKeyVaultSecret(credentials) {
    let keyVaultClient = new KeyVault.KeyVaultClient(credentials);
    return keyVaultClient.getSecret(KEY_VAULT_URI, 'secret', "");
}

getKeyVaultCredentials().then(
    getKeyVaultSecret
).then(function (secret){
    console.log(`Your secret value is: ${secret.value}.`);
}).catch(function (err) {
    throw (err);
});

I'd recommend checking the full documentation here

With the new Azure SDK for js, you can authenticate your application with managed service by implementing class DefaultAzureCredential from package @azure/identity.

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

const credential = new DefaultAzureCredential();
  
const vaultName = "<key-vault-name>";
const url = `https://${vaultName}.vault.azure.net`;
  
const client = new SecretClient(url, credential);

client.setSecret(secretName, "MySecretValue");
........

It supports both service principal and managed identity authentication.

To run it on a local environment you must set three environment variables: AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET to be able to connect with a service principal.

On Azure, if those variables are not defined, it will try to authenticate with managed identity.

There is a quickstart guide here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!