将密钥和机密存储在 Azure 密钥保管库中

Store key and secret in Azure key-vault

我们希望将 AWS 密钥和机密存储在 Azure Key Vault 中,因为我们的 VM 在 Azure 云中。

我们只想将 AWS 秘密和密钥保存在 Azure 密钥库中,而不是在环境变量中设置它们。

然后,我们想通过代码中的 API 访问它们。

我对 Azure Key Vault 还很陌生,想知道它是否可行?一个简单的 example/reference 会有很大帮助。

这是可能的,只需将它们存储在 azure keyvault 中并通过 VM MSI(VM 系统分配的托管标识)访问它们。

参考 - Use a Windows VM system-assigned managed identity to access Azure Key Vault

完成先决条件并授予 MSI 的访问权限,在 VM 中,您可以获得令牌并使用令牌获取机密。

查看下面的powershell示例,你也可以使用其他语言,逻辑是一样的,这取决于你的需求。

$response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.net' -Method GET -Headers @{Metadata="true"}     
$content = $response.Content | ConvertFrom-Json     
$KeyVaultToken = $content.access_token     
(Invoke-WebRequest -Uri https://<your-key-vault-URL>/secrets/<secret-name>?api-version=2016-10-01 -Method GET -Headers @{Authorization="Bearer $KeyVaultToken"}).content 

回复:

{"value":"p@ssw0rd!","id":"https://mytestkeyvault.vault.azure.net/secrets/MyTestSecret/7c2204c6093c4d859bc5b9eff8f29050","attributes":{"enabled":true,"created":1505088747,"updated":1505088747,"recoveryLevel":"Purgeable"}} 

更新:

您需要将 VM MSI 添加到密钥库的 Access Policies

Azure KeyVault 具有客户端库,您可以使用它从您的应用程序与 KeyVault 进行交互。

例如,这些是与 .NET, Java, Python and TypeScript

中的 KeyVault Secrets 交互的客户端库

以下是使用 .NET 从 KeyVault 检索机密的方法:

// Environment variable with the Key Vault endpoint.
string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

// create the client to interact with the service
var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

KeyVaultSecret secretWithValue = await client.GetSecretAsync("mySecret");
Console.WriteLine(secretWithValut.Value);

有关详细信息,请查看 .NET 存储库中的 samples 页面。