簡體   English   中英

如何在節點中使用 Azure 托管服務標識訪問 Key Vault?

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

我按照此處的說明創建托管服務標識。 所以現在在我的環境變量中,我有 MSI_ENDPOINT 和 MSI_SECRET。

在我的 typescript (node.js) 項目中,我導入了以下項目:

import {KeyVaultCredentials, KeyVaultClient} from "azure-keyvault";
import {AuthenticationContext, ErrorResponse, TokenResponse} from "adal-node";

如果我沒有使用 MSI,我可以使用以下代碼訪問我的密鑰保管庫:

let keyVaultCredentials = new KeyVaultCredentials(KeyVault.createAuthenticator(this.clientID, this.clientKey));
let keyVaultClient = new KeyVaultClient(keyVaultCredentials);
private static createAuthenticator(clientID: string, clientKey: string){
  return (challenge, callback) => {
  let context = new AuthenticationContext(challenge.authorization);
  return context.acquireTokenWithClientCredentials(
      challenge.resource,
      clientID,
      clientKey,
      function (err, tokenResponse:TokenResponse | ErrorResponse) {
          if (err) {
              CLogger.log("error", "Error occurred while acquiring token with key vault credentials: " + JSON.stringify(err));
              throw new Error("Error occurred while acquiring token with key vault credentials. Check log files");
          }
          if(<TokenResponse>tokenResponse){
              let authorizationValue = (<TokenResponse>tokenResponse).tokenType + " " + (<TokenResponse>tokenResponse).accessToken;
              return callback(null, authorizationValue);
          }
      });
  }
}

我不知道如何在啟用 MSI 的情況下獲取訪問令牌,請幫忙。

使用適用於 js 的新 Azure SDK,你可以通過實現包 @azure/identity 中的 DefaultAzureCredential 類來使用托管服務對應用程序進行身份驗證。

 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"); ........

它支持服務主體和托管身份驗證。

要在本地環境中運行它,您必須設置三個環境變量:AZURE_TENANT_ID、AZURE_CLIENT_ID 和 AZURE_CLIENT_SECRET,以便能夠與服務主體連接。

在 Azure 上,如果未定義這些變量,它將嘗試使用托管標識進行身份驗證。

有一個快速入門指南這里

使用 ms-rest-azure 中的 loginWithAppServiceMSI() 方法將自動檢測您是否在 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);
});

我建議在此處查看完整文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM