快速入门:适用于 Python 的 Azure Key Vault 证书客户端库Quickstart: Azure Key Vault certificates client library for Python

适用于 Python 的 Azure Key Vault 客户端库入门。Get started with the Azure Key Vault client library for Python. 请遵循以下步骤安装包并试用基本任务的示例代码。Follow the steps below to install the package and try out example code for basic tasks. 通过使用 Key Vault 存储证书,可以避免在代码中存储证书,从而提高应用的安全性。By using Key Vault to store certificates, you avoid storing certificates in your code, which increases the security of your app.

API 参考文档 | 库源代码 | 包(Python 包索引)API reference documentation | Library source code | Package (Python Package Index)

设置本地环境Set up your local environment

  1. 请确保你具有活动订阅的 Azure 帐户Make sure you have an Azure account with an active subscription.

  2. 安装 Python 2.7+ 或 3.5.3+Install Python 2.7+ or 3.5.3+.

  3. 安装 Azure CLIInstall the Azure CLI.

  4. 按照为本地开发配置身份验证的说明操作,使用该说明创建本地服务主体,并通过环境变量将其提供给 Python 的 Azure Key Vault 客户端。Follow the instructions on Configure authentication for local development, with which you create a local service principal and make it available to the Azure Key Vault Client for Python through environment variables.

    直接在 Azure 上运行代码时,如果应用使用托管标识,则不需要单独的服务主体。When running code directly on Azure, a separate service principal is not needed if the app uses managed identity.

  5. 在终端或命令提示符中,创建合适的项目文件夹,然后创建并激活 Python 虚拟环境,如使用 Python 虚拟环境中所述In a terminal or command prompt, create a suitable project folder, and then create and activate a Python virtual environment as described on Use Python virtual environments

  6. 安装 Azure Active Directory 标识库:Install the Azure Active Directory identity library:

    pip install azure.identity
    
  1. 安装 Key Vault 证书库:Install the Key Vault certificates library:

    pip install azure-keyvault-certificates
    

创建资源组和 Key VaultCreate a resource group and key vault

  1. 使用 az group create 命令以创建资源组:Use the az group create command to create a resource group:

    az group create --name KeyVault-PythonQS-rg --location chinaeast
    

    如果愿意,你可以将“chinaeast”更改为离你更近的位置。You can change "chinaeast" to a location nearer to you, if you prefer.

  2. 使用 az keyvault create 创建密钥保管库:Use az keyvault create to create the key vault:

    az keyvault create --name <your-unique-keyvault-name> --resource-group KeyVault-PythonQS-rg
    

    <your-unique-keyvault-name> 替换为在整个 Azure 中均唯一的名称。Replace <your-unique-keyvault-name> with a name that's unique across all of Azure. 通常使用个人或公司名称以及其他数字和标识符。You typically use your personal or company name along with other numbers and identifiers.

  3. 创建用于向代码提供 Key Vault 名称的环境变量:Create an environment variable that supplies the name of the Key Vault to the code:

    set KEY_VAULT_NAME=<your-unique-keyvault-name>
    

为服务主体授予对 Key Vault 的访问权限Give the service principal access to your key vault

运行以下 az keyvault set-policy 命令,以授权服务主体对证书进行获取、列出和创建操作。Run the following az keyvault set-policy command to authorize your service principal for get, list, and create operations on certificates.

az keyvault set-policy --name %KEY_VAULT_NAME% --spn %AZURE_CLIENT_ID% --resource-group KeyVault-PythonQS-rg --certificate-permissions delete get list create

此命令依赖前面步骤中创建的 KEY_VAULT_NAMEAZURE_CLIENT_ID 环境变量。This command relies on the KEY_VAULT_NAME and AZURE_CLIENT_ID environment variables created in previous steps.

有关详细信息,请参阅分配访问策略 - CLIFor more information, see Assign an access policy - CLI

创建示例代码Create the sample code

使用适用于 Python 的 Azure Key Vault 客户端库,可以管理证书和相关的资产(例如机密和加密密钥)。The Azure Key Vault client library for Python allows you to manage certificates and related assets such as secrets and cryptographic keys. 以下代码示例演示如何创建客户端以及设置、检索和删除机密。The following code sample demonstrates how to create a client, set a secret, retrieve a secret, and delete a secret.

创建包含此代码的名为 kv_certificates.py 的文件。Create a file named kv_certificates.py that contains this code.

import os
from azure.keyvault.certificates import CertificateClient, CertificatePolicy,CertificateContentType, WellKnownIssuerNames 
from azure.identity import DefaultAzureCredential

keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = "https://" + keyVaultName + ".vault.azure.cn"

credential = DefaultAzureCredential()
client = CertificateClient(vault_url=KVUri, credential=credential)

certificateName = input("Input a name for your certificate > ")

print(f"Creating a certificate in {keyVaultName} called '{certificateName}' ...")

policy = CertificatePolicy.get_default()
poller = client.begin_create_certificate(certificate_name=certificateName, policy=policy)
certificate = poller.result()

print(" done.")

print(f"Retrieving your certificate from {keyVaultName}.")

retrieved_certificate = client.get_certificate(certificateName)

print(f"Certificate with name '{retrieved_certificate.name}' was found'.")
print(f"Deleting your certificate from {keyVaultName} ...")

poller = client.begin_delete_certificate(certificateName)
deleted_certificate = poller.result()

print(" done.")

运行代码Run the code

确保上一部分中的代码位于名为 kv_certificates.py 的文件中。Make sure the code in the previous section is in a file named kv_certificates.py. 然后,使用以下命令运行代码:Then run the code with the following command:

python kv_certificates.py
  • 如果遇到权限错误,请确保已运行 az keyvault set-policy 命令If you encounter permissions errors, make sure you ran the az keyvault set-policy command.
  • 重新运行具有相同密钥名称的代码可能会产生错误:“(冲突)证书 当前处于已删除但可恢复的状态。”Re-running the code with the same key name may produce the error, "(Conflict) Certificate is currently in a deleted but recoverable state." 使用其他密钥名称。Use a different key name.

代码详细信息Code details

进行身份验证并创建客户端Authenticate and create a client

在前面的代码中,DefaultAzureCredential 对象使用针对服务主体创建的环境变量。In the preceding code, the DefaultAzureCredential object uses the environment variables you created for your service principal. 每当从 Azure 库创建客户端对象(例如 CertificateClient)以及要通过该客户端使用的资源的 URI 时,都要提供此凭据:You provide this credential whenever you create a client object from an Azure library, such as CertificateClient, along with the URI of the resource you want to work with through that client:

credential = DefaultAzureCredential()
client = CertificateClient(vault_url=KVUri, credential=credential)

保存证书Save a certificate

获取密钥保管库的客户端对象后,可以使用 begin_create_certificate 方法来创建证书:Once you've obtained the client object for the key vault, you can create a certificate using the begin_create_certificate method:

policy = CertificatePolicy.get_default()
poller = client.begin_create_certificate(certificate_name=certificateName, policy=policy)
certificate = poller.result()

此处,证书要求使用 CertificatePolicy get_default 方法来获取策略。Here, the certificate requires a policy obtained with the CertificatePolicy.get_default method.

调用 begin_create_certificate 方法会生成对密钥保管库的 Azure REST API 的异步调用。Calling a begin_create_certificate method generates an asynchronous call to the Azure REST API for the key vault. 异步调用会返回一个轮询器对象。The asynchronous call returns a poller object. 若要等待操作的结果,请调用轮询器的 result 方法。To wait for the result of the operation, call the poller's result method.

在处理请求时,Azure 使用你提供给客户端的凭据对象,对调用方的标识(服务主体)进行身份验证。When handling the request, Azure authenticates the caller's identity (the service principal) using the credential object you provided to the client.

它还将检查调用方是否有权执行请求的操作。It also checks that the caller is authorized to perform the requested action. 先前使用 az keyvault set-policy 命令向服务主体授予了此授权。You granted this authorization to the service principal earlier using the az keyvault set-policy command.

检索证书Retrieve a certificate

若要从 Key Vault 读取证书,请使用 get_certificate 方法:To read a certificate from Key Vault, use the get_certificate method:

retrieved_certificate = client.get_certificate(certificateName)

还可以使用 Azure CLI 命令 az keyvault certificate show 来验证是否设置了证书。You can also verify that the certificate has been set with the Azure CLI command az keyvault certificate show.

删除证书Delete a certificate

若要删除证书,请使用 begin_delete_certificate 方法:To delete a certificate, use the begin_delete_certificate method:

poller = client.begin_delete_certificate(certificateName)
deleted_certificate = poller.result()

begin_delete_certificate 方法是异步方法,将返回一个轮询器对象。The begin_delete_certificate method is asynchronous and returns a poller object. 调用轮询器的 result 方法等待其完成。Calling the poller's result method waits for its completion.

可以使用 Azure CLI 命令 az keyvault certificate show 来验证是否已删除证书。You can verify that the certificate is deleted with the Azure CLI command az keyvault certificate show.

证书删除后,会在一段时间内保持已删除但可恢复状态。Once deleted, a certificate remains in a deleted but recoverable state for a time. 如果再次运行该代码,请使用其他证书名称。If you run the code again, use a different certificate name.

清理资源Clean up resources

如果还想试验机密密钥,可以重复使用本文中创建的 Key Vault。If you want to also experiment with secrets and keys, you can reuse the Key Vault created in this article.

否则,当完成本文中创建的资源后,请使用以下命令删除资源组及其包含的所有资源:Otherwise, when you're finished with the resources created in this article, use the following command to delete the resource group and all its contained resources:

az group delete --resource-group KeyVault-PythonQS-rg

后续步骤Next steps