从带有MSI的linux vm节点获取azure keyvault的秘密

问题描述 投票:0回答:1

我在使用azure上的linux vm上运行的节点应用程序中的azure-keyvault软件包从azure keyvault获取秘密时遇到问题。

我使用以下代码:

import * as KeyVault from 'azure-keyvault';
import * as msRestAzure from 'ms-rest-azure'

function getKeyVaultCredentials(){
    return msRestAzure.loginWithVmMSI();
}

function getKeyVaultSecret(credentials) {
    let keyVaultClient = new KeyVault.KeyVaultClient(credentials,null);
    return keyVaultClient.getSecret("my keyvault url here", 'my keyvault secret name here', "", null,null);
}

getKeyVaultCredentials().then(
    getKeyVaultSecret
).then(function (secret){
    //not getting here....
}).catch(function (err) {
    //...error handling...
});

我在调用getSecret时收到401响应。在keyvault和MSI上为计算机设置了权限。在错误中我得到的似乎没有任何标头的身份验证或令牌,虽然我确实看到一个标题看起来像响应上的身份验证标头。

我的实施中是否有任何遗漏?

编辑:如果我愿意,看起来我在这里分享的例子会有用

msRestAzure.loginWithVmMSI({resource: 'https://vault.azure.net' });

而不是没有参数调用它。

node.js typescript azure azure-keyvault
1个回答
2
投票

在您的keyvault中,请确保已使用正确的密钥权限添加了Access policies中的服务主体(通过启用MSI自动创建)。然后尝试单击Click to show advanced access policies->选择Enable access to Azure Virtual Machines for deployment选项 - >保存。

这是一个代码示例,您可以检查检索秘密值的部分。

var http = require('http');
const KeyVault = require('azure-keyvault');
const msRestAzure = require('ms-rest-azure');


var server = http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
});

// The ms-rest-azure library allows us to login with MSI by providing the resource name. In this case the resource is Key Vault.
// For public regions the resource name is Key Vault
msRestAzure.loginWithAppServiceMSI({resource: 'https://vault.azure.net'}).then( (credentials) => {
    const keyVaultClient = new KeyVault.KeyVaultClient(credentials);

    var vaultUri = "https://" + "<YourVaultName>" + ".vault.azure.net/";

    // We're setting the Secret value here and retrieving the secret value
    keyVaultClient.setSecret(vaultUri, 'my-secret', 'test-secret-value', {})
        .then( (kvSecretBundle, httpReq, httpResponse) => {
            console.log("Secret id: '" + kvSecretBundle.id + "'.");
            return keyVaultClient.getSecret(kvSecretBundle.id, {});
        })
        .then( (bundle) => {
            console.log("Successfully retrieved 'test-secret'");
            console.log(bundle);
        })
        .catch( (err) => {
            console.log(err);
        });

    // Below code demonstrates how to retrieve a secret value

    // keyVaultClient.getSecret(vaultUri, "AppSecret", "").then(function(response){
    //     console.log(response);    
    // })
});

有关更多详细信息,请参阅:Set and retrieve a secret from Azure Key Vault using a Node Web App

© www.soinside.com 2019 - 2024. All rights reserved.