快速入門:適用於 .NET 的 Azure Key Vault 秘密用戶端程式庫

開始使用適用於 .NET 的 Azure Key Vault 秘密用戶端程式庫。 Azure Key Vault 是一項雲端服務,可為祕密提供安全的存放區。 您也可以安全地儲存金鑰、密碼、憑證和其他祕密。 您可以透過 Azure 入口網站建立和管理 Azure 金鑰保存庫。 在本快速入門中,您會了解如何使用 .NET 用戶端程式庫,從 Azure Key Vault 建立、擷取和刪除秘密

Key Vault 用戶端程式庫資源:

API 參考文件 | 程式庫原始程式碼 | 套件 (NuGet)

如需有關 Key Vault 及秘密的詳細資訊,請參閱:

必要條件

本快速入門使用的是 dotnet 和 Azure CLI 或 Azure PowerShell。

設定

本快速入門會使用 Azure 身分識別程式庫搭配 Azure CLI,向 Azure 服務驗證使用者。 開發人員也可以使用 Visual Studio 或 Visual Studio Code 來驗證其呼叫。如需詳細資訊,請參閱使用 Azure 身分識別用戶端程式庫驗證用戶端

登入 Azure

  1. 執行 az login 命令。

    az login
    

    如果此 CLI 可以開啟您的預設瀏覽器,它會開啟瀏覽器並載入 Azure 登入頁面。

    否則,請在 https://aka.ms/devicelogin 中開啟瀏覽器頁面,並輸入顯示在您的終端機中的授權碼。

  2. 請在瀏覽器中使用您的帳戶認證登入。

授與對金鑰保存庫的存取權

若要透過角色型 存取控制 (RBAC) 將應用程式許可權授與密鑰保存庫,請使用 Azure CLI 命令 az role assignment create 來指派角色。

az role assignment create --role "Key Vault Secrets User" --assignee "<app-id>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

將 app-id、subscription-id>>、<<resource-group-name 和 <your-unique-keyvault-name>> 取代<為您的實際值。 <app-id> 是 Azure AD 中已註冊應用程式的應用程式(用戶端)標識碼。

建立新的 .NET 主控台應用程式

  1. 在命令殼層中,執行下列命令以建立名為 key-vault-console-app 的專案:

    dotnet new console --name key-vault-console-app
    
  2. 變更為新建立的 key-vault-console-app 目錄,然後執行下列命令來建置專案:

    dotnet build
    

    建置輸出應該不會有警告或錯誤。

    Build succeeded.
     0 Warning(s)
     0 Error(s)
    

安裝套件

從命令殼層安裝適用於 .NET 的 Azure Key Vault 秘密用戶端程式庫:

dotnet add package Azure.Security.KeyVault.Secrets

針對本快速入門,您也需要安裝 Azure Identity 用戶端程式庫:

dotnet add package Azure.Identity

設定環境變數

此應用程式使用金鑰保存庫名稱作為稱為 KEY_VAULT_NAME 的環境變數。

Windows

set KEY_VAULT_NAME=<your-key-vault-name>

Windows PowerShell

$Env:KEY_VAULT_NAME="<your-key-vault-name>"

macOS 或 Linux

export KEY_VAULT_NAME=<your-key-vault-name>

物件模型

適用於 .NET 的 Azure Key Vault 秘密用戶端程式庫可讓您管理秘密。 以下的程式碼範例會示範如何建立用戶端、設定祕密、擷取祕密,以及刪除秘密。

程式碼範例

新增指示詞

將下列指示詞新增至 Program.cs 的上方:

using System;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

驗證並建立用戶端

對大部分 Azure 服務的應用程式要求都必須獲得授權。 在程式碼中實作對 Azure 服務的無密碼連線時,建議使用 Azure.Identity 用戶端程式庫提供的 DefaultAzureCredential 類別。 DefaultAzureCredential 支援多個驗證方法,並在執行階段判斷應該使用哪個方法。 此方法可讓您的應用程式在不同的環境中 (本機或實際執行環境) 使用不同的驗證方法,而不需要實作環境特有的程式碼。

在本快速入門中,DefaultAzureCredential 使用已登入 Azure CLI 之本機開發使用者的認證向金鑰保存庫進行驗證。 將應用程式部署至 Azure 時,相同的 DefaultAzureCredential 程式碼可以自動探索並使用指派給 App Service、虛擬機器或其他服務的受控識別。 如需詳細資訊,請參閱受控識別概觀

在此範例中,金鑰保存庫的名稱會以 https://<your-key-vault-name>.vault.azure.net 格式,擴充至金鑰保存庫 URI。 如需對金鑰保存庫進行驗證的詳細資訊,請參閱開發人員指南

string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.net";

var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());

儲存秘密

既然主控台應用程式已通過驗證,請將秘密新增至金鑰保存庫。 針對這項工作,使用 SetSecretAsync 方法。

方法的第一個參數會接受秘密的名稱。 在此範例中,變數 secretName 會儲存 "mySecret" 字串。

方法的第二個參數接受秘密的值。 在此範例中,秘密是使用者透過命令列輸入並儲存在變數 secretValue

await client.SetSecretAsync(secretName, secretValue);

注意

如果秘密名稱存在,則程式碼會建立該秘密的新版本。

擷取祕密

您現在可以使用 GetSecretAsync 方法來擷取先前設定的值。

var secret = await client.GetSecretAsync(secretName);

您的祕密現在已另存為 secret.Value

刪除祕密

最後,讓我們使用 StartDeleteSecretAsyncPurgeDeletedSecretAsync 方法,從您的金鑰保存庫中刪除祕密。

var operation = await client.StartDeleteSecretAsync(secretName);
// You only need to wait for completion if you want to purge or recover the key.
await operation.WaitForCompletionAsync();

await client.PurgeDeletedSecretAsync(secretName);

範例指令碼

請完成下列步驟來修改 .NET 主控台應用程式,以與 Key Vault 互動:

  1. Program.cs 中的程式碼取代為下列程式碼:

    using System;
    using System.Threading.Tasks;
    using Azure.Identity;
    using Azure.Security.KeyVault.Secrets;
    
    namespace key_vault_console_app
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                const string secretName = "mySecret";
                var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
                var kvUri = $"https://{keyVaultName}.vault.azure.net";
    
                var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
    
                Console.Write("Input the value of your secret > ");
                var secretValue = Console.ReadLine();
    
                Console.Write($"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ...");
                await client.SetSecretAsync(secretName, secretValue);
                Console.WriteLine(" done.");
    
                Console.WriteLine("Forgetting your secret.");
                secretValue = string.Empty;
                Console.WriteLine($"Your secret is '{secretValue}'.");
    
                Console.WriteLine($"Retrieving your secret from {keyVaultName}.");
                var secret = await client.GetSecretAsync(secretName);
                Console.WriteLine($"Your secret is '{secret.Value.Value}'.");
    
                Console.Write($"Deleting your secret from {keyVaultName} ...");
                DeleteSecretOperation operation = await client.StartDeleteSecretAsync(secretName);
                // You only need to wait for completion if you want to purge or recover the secret.
                await operation.WaitForCompletionAsync();
                Console.WriteLine(" done.");
    
                Console.Write($"Purging your secret from {keyVaultName} ...");
                await client.PurgeDeletedSecretAsync(secretName);
                Console.WriteLine(" done.");
            }
        }
    }
    

測試和驗證

  1. 執行下列命令來執行應用程式。

    dotnet run
    
  2. 當系統提示時,輸入祕密值。 例如,mySecretPassword。

隨即出現下列輸出的變化:

Input the value of your secret > mySecretPassword
Creating a secret in <your-unique-keyvault-name> called 'mySecret' with the value 'mySecretPassword' ... done.
Forgetting your secret.
Your secret is ''.
Retrieving your secret from <your-unique-keyvault-name>.
Your secret is 'mySecretPassword'.
Deleting your secret from <your-unique-keyvault-name> ... done.    
Purging your secret from <your-unique-keyvault-name> ... done.

下一步

若要深入了解 Key Vault 以及如何將其與應用程式整合,請參閱下列文章: