如何在节点中使用Azure托管服务身份访问Key Vault?
我遵循此处的说明创建托管服务标识。所以现在在我的环境变量中,我有MSI_ENDPOINT和MSI_SECRET。
I follow the instruction here to create an Managed Service Identity. So now in my environment variable, I have MSI_ENDPOINT and MSI_SECRET.
在我的打字稿(node.js)项目中,我导入了以下项目:
In my typescript (node.js) project, I imported the following project:
import {KeyVaultCredentials, KeyVaultClient} from "azure-keyvault";
import {AuthenticationContext, ErrorResponse, TokenResponse} from "adal-node";
如果我不使用MSI,则可以使用以下代码访问我的密钥库:
If I wasn't using MSI, I could access my key vault using the following code:
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获取访问令牌
I have no idea how to get access token with MSI enabled, please help.
使用适用于js的新Azure SDK,您可以通过实现类DefaultAzureCredential来使用托管服务对应用程序进行身份验证
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.
要在本地环境中运行它必须设置三个环境变量:AZURE_TENANT_ID,AZURE_CLIENT_ID和AZURE_CLIENT_SECRET才能连接服务主体。
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.
在Azure上,如果未定义这些变量,它将尝试
On Azure, if those variables are not defined, it will try to authenticate with managed identity.
有一个快速入门指南此处。