使用loginWithAppServiceMSI()
ms-rest-azure 中的方法将自动检测您是否在 WebApp 上并从 MSI 端点获取令牌。然后,代码很简单:
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);
});
如果您需要一种回退机制来允许此代码自动从 MSI 切换到另一种方法,您可以测试环境变量:
function getKeyVaultCredentials(){
if (process.env.APPSETTING_WEBSITE_SITE_NAME){
return msRestAzure.loginWithAppServiceMSI({resource: 'https://vault.azure.net'});
} else {
return msRestAzure.loginWithServicePrincipalSecret(clientId, secret, domain);
}
}