对 Azure Key Vault 进行身份验证Authenticate to Azure Key Vault

概述Overview

Azure Key Vault 是一个机密管理解决方案,你可以使用该解决方案集中存储应用程序机密并控制其分发。Azure Key Vault is a secrets management solution that allows you to centralize the storage of application secrets and control their distribution. Azure Key Vault 无需在应用程序中存储凭据。Azure Key Vault eliminates the need to store credentials in applications. 应用程序可以对密钥保管库进行身份验证,以检索所需的凭据。Your application can authenticate to key vault to retrieve the required credentials. 本文档将介绍对密钥保管库进行身份验证的基础知识。This document will cover the basics of authentication to key vault.

本文档将帮助你了解密钥保管库身份验证的工作原理。This document will help you understand how key vault authentication works. 本文档将介绍身份验证流,向你展示如何授予对密钥保管库的访问权限,并包括一个关于从示例 python 应用程序检索密钥保管库中的存储机密的教程。This document will explain the authentication flow, show you how to grant access to your key vault, and includes a tutorial to retrieve a stored secret in key vault from a sample python application.

本文档将介绍:This document will cover:

  • 关键概念Key Concepts
  • 安全主体注册Security Principal Registration
  • 了解 Key Vault 身份验证流Understanding Key Vault authentication flow
  • 为服务主体授予对 Key Vault 的访问权限Grant a service principal access to Key Vault
  • 教程 (Python)Tutorial (Python)

关键概念Key Concepts

Azure Active Directory 概念Azure Active Directory Concepts

  • Azure Active Directory (AAD) - Azure Active Directory (Azure AD) 是 Microsoft 推出的基于云的标识和访问管理服务,可帮助员工登录及访问以下位置的资源Azure Active Directory (AAD) - Azure Active Directory (Azure AD) is Microsoft’s cloud-based identity and access management service, which helps your employees sign in and access resources

  • 角色定义 - 角色定义是权限的集合。Role Definition - A role definition is a collection of permissions. AAD 具有标准角色(所有者、参与者或阅读者),这些角色包含对 Azure 资源执行读取、写入和删除等操作的权限级别。AAD has standard roles (Owner, Contributor, or Reader) that contain levels of permissions to perform operations like read, write, and delete on an Azure resource. 角色也可以是具有特定粒度权限的用户创建的自定义定义。Roles can also be custom definitions created by users with specific granular permissions.

  • 应用程序注册 - 注册 Azure AD 应用程序时,会在 Azure AD 租户中创建两个对象:应用程序对象和服务主体对象。Application Registration - When you register an Azure AD application, two objects are created in your Azure AD tenant, an application object and a service principal object. 可以将应用程序对象视为应用程序的全局表示形式(供所有租户使用),将服务主体视为本地表示形式(在特定租户中使用)。Consider the application object as the global representation of your application for use across all tenants, and the service principal as the local representation for use in a specific tenant.

安全主体概念Security Principal Concepts

  • 安全主体 - 安全主体是一个对象,表示请求访问 Azure 资源的用户、组、服务主体或托管标识。Security Principal - A security principal is an object that represents a user, group, service principal, or managed identity that is requesting access to Azure resources.

  • 用户 - 在 Azure Active Directory 中具有配置文件的人员。User - An individual who has a profile in Azure Active Directory.

  • 组 - 在 Azure Active Directory 中创建的一组用户。Group - A set of users created in Azure Active Directory. 将某个角色分配到某个组时,该组中的所有用户都拥有该角色。When you assign a role to a group, all users within that group have that role.

  • 服务主体 - 应用程序或服务用来访问特定 Azure 资源的安全标识。Service principal - A security identity used by applications or services to access specific Azure resources. 可将服务主体视为应用程序的用户标识(用户名和密码或证书)。You can think of it as a user identity (username and password or certificate) for an application.

  • 托管标识 - Azure Active Directory 中由 Azure 自动托管的标识。Managed Identity - An identity in Azure Active Directory that is automatically managed by Azure.

  • 对象 ID(客户端 ID)- Azure AD 生成的唯一标识符,在其初始预配期间与服务主体绑定。Object ID (Client ID) - a unique identifier generated by Azure AD that is tied to a service principal during its initial provisioning.

安全主体注册Security Principal Registration

  1. 管理员在 Azure Active Directory 中注册用户或应用程序(服务主体)。Administrator registers a user or application (service principal) in Azure Active Directory.

  2. 管理员创建 Azure Key Vault 并配置访问策略 (ACL)。Administrator creates an Azure Key Vault and configures access policies (ACLs).

  3. (可选)管理员配置 Azure Key Vault 防火墙。(Optional) Administrator configures the Azure Key Vault Firewall.

图像

了解 Key Vault 身份验证流Understand the Key Vault authentication flow

  1. 服务主体通过调用对 AAD 进行身份验证,这可能通过多种方式发生:A service principal makes a call to authenticate to AAD this can happen in several ways:

    • 用户可以使用用户名和密码登录到 Azure 门户。A user can log into the Azure portal using a username and password.
    • 应用程序使用客户端 ID,向 AAD 提供客户端机密或客户端证书An application uses a client ID and presents a client secret or client certificate to AAD
    • Azure 资源(如虚拟机)具有分配的 MSI,并联系 IMDS REST 终结点以获取访问令牌。An Azure resource such as a virtual machine has an assigned MSI and contacts the IMDS REST endpoint to get an access token.
  2. 如果对 AAD 的身份验证成功,将向服务主体授予 OAuth 令牌。If authentication to AAD is successful, the service principal will be granted an OAuth token.

  3. 服务主体调用 Key Vault。The service principal makes a call to Key Vault.

  4. Azure Key Vault 防火墙决定是否允许调用。Azure Key Vault Firewall determines whether to allow the call.

    • 应用场景 1:Key Vault 防火墙已禁用,可从公共 Internet 访问密钥保管库的公共终结点 (URI)。Scenario 1: Key Vault Firewall is disabled, public endpoint (URI) of key vault is reachable from the public internet. 调用是被允许的。Call is allowed.
    • 应用场景 2:调用方是 Azure Key Vault 信任的服务。Scenario 2: Caller is an Azure Key Vault trusted service. 如果选择了此选项,某些 Azure 服务可以绕过密钥保管库防火墙。Certain Azure services can bypass the key vault firewall if the option is selected. Key Vault 信任的服务列表Key Vault Trusted Service List
    • 应用场景 3:调用方按 IP 地址、虚拟网络或服务终结点在 Azure Key Vault 防火墙中列出。Scenario 3: Caller is listed in the Azure Key Vault firewall by IP address, virtual network, or service endpoint.
    • 应用场景 4:调用方可以通过配置的专用链接连接访问 Azure Key Vault。Scenario 4: Caller can reach Azure Key Vault over a configured private link connection.
    • 应用场景 5:调用方未获得授权,返回“被禁止”响应。Scenario 5: Caller is not authorized and a forbidden response is returned.
  5. Key Vault 调用 AAD 以验证服务主体的访问令牌。Key Vault makes a call to AAD to validate the service principal’s access token.

  6. Key Vault 检查服务主体是否具有执行请求操作的足够访问策略权限,在此示例中,该操作是获取机密。Key Vault checks if the service principal has sufficient access policy permissions to perform the requested operation, in this example, the operation is get secret.

  7. Key Vault 向服务主体提供机密。Key Vault provides the secret to the service principal.

IMAGE

为服务主体授予对 Key Vault 的访问权限Grant a service principal access to Key Vault

  1. 如果尚未创建服务主体,请创建一个。Create a service principal if you don't already have one. 创建服务主体Create a Service Principal
  2. 在 Azure Key Vault IAM 设置中向服务主体添加角色分配。Add a role assignment to your service principal in the Azure Key Vault IAM settings. 可以添加以下预分配角色:所有者、参与者或读取者。You can add pre-assigned roles of Owner, Contributor, or Reader. 还可以为服务主体创建自定义角色。You can also create custom roles for your service principal. 应遵循最小特权主体,并且只提供服务主体所需的最低访问权限。You should follow the principal of least privilege and only provide the minimum access necessary for your service principal.
  3. 配置密钥保管库防火墙。Configure the key vault firewall. 可以禁用密钥保管库防火墙,并允许从公共 Internet 访问(不太安全,更易于配置)。You can keep the key vault firewall disabled and allow access from the public internet (less secure, easier to configure). 还可以限制对特定 IP 范围、服务终结点、虚拟网络或专用终结点的访问(更安全)。You can also restrict access to specific IP ranges, service endpoints, virtual networks, or private endpoints (more secure).
  4. 为服务主体添加访问策略,这是服务主体可以在密钥保管库上执行的操作列表。Add an access policy for your service principal, this is a list of operations that your service principal can perform on the key vault. 应使用最小特权主体,并限制服务主体可以执行的操作。You should use the principal of least-privilege and limit the operations that the service principal can perform. 但是,如果你没有提供足够的权限,服务主体的访问将被拒绝。However, if you do not provide sufficient permissions, your service principal will be denied access.

教程Tutorial

在本教程中,你将了解如何设置服务主体以对密钥保管库进行身份验证库并检索机密。In this tutorial you will learn how to set up a service principal to authenticate to key vault and retrieve a secret.

第 1 部分:在 Azure 门户创建服务主体Part 1: Create a Service Principal in the Azure portal

  1. 登录到 Azure 门户Log in to the Azure portal
  2. 搜索“Azure Active Directory”Search for Azure Active Directory
  3. 单击“应用注册”选项卡Click the “App Registrations” Tab
  4. 单击“+ 新建注册”Click “+ New Registration”
  5. 创建服务主体的名称Create a name for the service principal
  6. 选择“注册”Select Register

此时,你有一个已注册的服务主体。At this point you have a registered service principal. 可以通过选择“应用注册”来查看它。You can view it by selecting “App Registrations”. 现在,服务主体将分配有客户端 ID GUID,可以将其视为服务主体的“用户名”。Your service principal will now be assigned a client ID GUID, think of this as a “username” for your service principal. 现在我们需要为服务主体创建一个“密码”,你可以使用客户端密码或客户端证书。Now we need to create a “password” for your service principal, you can use a client secret or a client certificate. 请注意,使用客户端密码进行身份验证不安全,应仅用于测试目的。Note, using a client secret for authentication is not secure and should only be used for testing purposes. 本教程将演示如何使用客户端证书。This tutorial will show you how to use a client certificate.

第 2 部分:为服务主体创建客户端证书Part 2: Create a client certificate for your service principal

  1. 创建证书Create a certificate

    • 选项 1:使用 OpenSSL 创建证书(仅出于测试目的,请不要在生产中使用自签名证书)Option 1: Create a certificate using OpenSSL (for test purposes only, do not use self-signed certificates in production)
    openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
    
  2. 下载 PEM 格式的证书Download the certificate in the PEM format

  3. 登录到 Azure 门户,然后导航到 Azure Active DirectoryLog in to the Azure portal and navigate to Azure Active Directory

  4. 单击“应用注册”Click "App Registrations"

  5. 选择在第 1 部分中创建的服务主体。Select the service principal you created in Part 1.

  6. 单击服务主体的“证书和密码”选项卡Click on the “Certificates and Secrets” tab of your service principal

  7. 使用“上传证书”按钮上传证书Upload the certificate using the "Upload Certificate" button

第 3 部分:配置 Azure Key VaultPart 3: Configure an Azure Key Vault

  1. 创建 Azure Key Vault 链接Create an Azure Key Vault Link

  2. 配置 Key Vault IAM 权限Configure Key Vault IAM permissions

    1. 导航到你的密钥保管库Navigate to your key vault
    2. 选择“访问控制(IAM)”选项卡Select the “Access Control (IAM)” tab
    3. 单击“添加角色分配”Click Add Role Assignment
    4. 从下拉列表中选择“参与者”角色Select “Contributor” role from the dropdown
    5. 输入创建的服务主体的名称或客户端 IDEnter the name or client ID of the service principal you created
    6. 单击“查看角色分配”以确认你的服务主体已列出Click “View Role Assignments” to confirm your service principal is listed
  3. 配置 Key Vault 访问策略权限Configure Key Vault Access Policy permissions

    1. 导航到你的密钥保管库Navigate to your key vault
    2. 选择“设置”下的“访问策略”选项卡Select the “Access Policies” tab under “Settings”
    3. 选择“+ 添加访问策略”链接Select the “+ Add Access Policy” link
    4. 在“机密权限”下拉列表中,查看“获取”和“列出”权限。Under the Secret Permissions dropdown check “Get” and “List” permissions.
    5. 按名称或客户端 ID 选择服务主体。Select your service principal by name or client ID.
    6. 选择“添加”Select “Add”
    7. 选择“保存”Select “Save”
  4. 在密钥保管库中选择密码。Create a secret in your key vault.

    1. 导航到你的密钥保管库Navigate to your key vault
    2. 单击“设置”下的“密码”选项卡Click the “Secrets” tab under Settings
    3. 单击“+ 生成/导入”Click “+ Generate/Import”
    4. 为密码创建一个名称,在此示例中,我将把密码命名为“test”Create a name for the secret, in this example, I will name the secret “test”
    5. 为密码创建一个值,在此示例中,我将把值设置为“password123”Create a value for the secret, in this example, I will set a value of “password123”

现在,当你从本地计算机运行代码时,可以通过提供客户端 ID 和证书路径获取访问令牌来对密钥保管库进行身份验证。Now, when you run code from your local machine, your can authenticate to key vault by getting an access token by presenting the client ID and a path to the certificate.

第 4 部分:从应用程序中的 Azure Key Vault 检索密码 (Python)Part 4: Retrieve the secret from your Azure Key Vault in an application (Python)

使用以下代码示例测试应用程序是否可以使用配置的服务主体从密钥保管库检索机密。Use the following code sample to test whether your application can retrieve a secret from your key vault using the service principal you configured.

from azure.keyvault.secrets import SecretClient
from azure.identity import CertificateCredential


tenant_id = ""                                             ##ENTER AZURE TENANT ID
vault_url = "https://{VAULT NAME}.vault.azure.cn/"        ##ENTER THE URL OF YOUR KEY VAULT
client_id = ""                                             ##ENTER CLIENT ID OF SERVICE PRINCIPAL
cert_path = r"C:\Users\{USERNAME}\{PATH}\{CERT_NAME}.pem"  ##ENTER PATH TO CERTIFICATE

def main():

    #AUTHENTICATION TO AAD USING CLIENT ID AND CLIENT CERTIFICATE
    token = CertificateCredential(tenant_id= tenant_id, client_id=client_id, certificate_path=cert_path)

    #AUTHENTICATION TO KEY VAULT PRESENTING AAD TOKEN
    client = SecretClient(vault_url=vault_url, credential=token)

    #CALL TO KEY VAULT TO GET SECRET
    secret = client.get_secret('{SECRET_NAME}')            ##ENTER NAME OF SECRET IN KEY VAULT

    #GET PLAINTEXT OF SECRET
    print(secret.value)

#CALL MAIN()
if __name__ == "__main__":
    main()

IMAGE

后续步骤Next Steps

  1. 了解如何对密钥保管库身份验证错误进行故障排除。Learn how to troubleshoot key vault authentication errors. Key Vault 故障排除指南Key Vault Troubleshooting Guide