Inicio rápido: Biblioteca cliente de certificados de Azure Key Vault para .NET (SDK v4)Quickstart: Azure Key Vault certificate client library for .NET (SDK v4)
Empiece a trabajar con la biblioteca cliente de certificados de Azure Key Vault para .NET.Get started with the Azure Key Vault certificate client library for .NET. Azure Key Vault es un servicio en la nube que proporciona un almacén seguro para los certificados.Azure Key Vault is a cloud service that provides a secure store for certificates. Puede almacenar de forma segura claves, contraseñas, certificados y otros secretos.You can securely store keys, passwords, certificates, and other secrets. Las instancias de Azure Key Vault se pueden crear y administrar a través de Azure Portal.Azure key vaults may be created and managed through the Azure portal. En este inicio rápido, aprenderá a crear, recuperar y eliminar certificados de una instancia de Azure Key Vault mediante la biblioteca cliente de .NET.In this quickstart, you learn how to create, retrieve, and delete certificates from an Azure key vault using the .NET client library
Recursos de la biblioteca cliente de Key Vault:Key Vault client library resources:
Documentación de referencia de la API | Código fuente de la biblioteca | Paquete (NuGet)API reference documentation | Library source code | Package (NuGet)
Para más información sobre Key Vault y los certificados, consulte:For more information about Key Vault and certificates, see:
- Introducción a Azure Key VaultKey Vault Overview
- Introducción a los certificados.Certificates Overview.
Requisitos previosPrerequisites
- Una suscripción a Azure: cree una cuenta gratuita.An Azure subscription - create one for free
- SDK de .NET Core 3.1 o una versión posterior.NET Core 3.1 SDK or later
- CLI de AzureAzure CLI
- Un almacén de claves: puede crear uno mediante Azure Portal, la CLI de Azure o Azure PowerShell.A Key Vault - you can create one using Azure portal, Azure CLI, or Azure PowerShell.
En este inicio rápido se usa dotnet
y la CLI de Azure.This quickstart is using dotnet
and Azure CLI
ConfigurarSetup
En este inicio rápido se usa la biblioteca de identidades de Azure con la CLI de Azure para autenticar al usuario en los servicios de Azure.This quickstart is using Azure Identity library with Azure CLI to authenticate user to Azure Services. Los desarrolladores también pueden usar Visual Studio o Visual Studio Code para autenticar sus llamadas. Para más información, consulte Autenticación del cliente mediante la biblioteca cliente Azure Identity.Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.
Inicio de sesión en AzureSign in to Azure
Ejecute el comando
login
.Run thelogin
command.az login
Si la CLI puede abrir el explorador predeterminado, lo hará y cargará una página de inicio de sesión de Azure.If the CLI can open your default browser, it will do so and load an Azure sign-in page.
En caso contrario, abra una página del explorador en https://aka.ms/devicelogin y escriba el código de autorización que se muestra en el terminal.Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.
Inicie sesión con las credenciales de su cuenta en el explorador.Sign in with your account credentials in the browser.
Concesión de acceso al almacén de clavesGrant access to your key vault
Cree una directiva de acceso para el almacén de claves que conceda permisos de certificado a la cuenta de su usuarioCreate an access policy for your key vault that grants certificate permissions to your user account
az keyvault set-policy --name <your-key-vault-name> --upn user@domain.com --certificate-permissions delete get list create purge
Creación de una aplicación de consola de .NETCreate new .NET console app
En un shell de comandos, ejecute el siguiente comando para crear un proyecto llamado
key-vault-console-app
:In a command shell, run the following command to create a project namedkey-vault-console-app
:dotnet new console --name key-vault-console-app
Cambie al directorio key-vault-console-app recién creado y ejecute el comando siguiente para compilar el proyecto:Change to the newly created key-vault-console-app directory, and run the following command to build the project:
dotnet build
La salida de la compilación no debe contener advertencias ni errores.The build output should contain no warnings or errors.
Build succeeded. 0 Warning(s) 0 Error(s)
Instalación de los paquetesInstall the packages
En el shell de comandos, instale la biblioteca cliente de certificados de Azure Key Vault para .NET:From the command shell, install the Azure Key Vault certificate client library for .NET:
dotnet add package Azure.Security.KeyVault.Certificates
Para este inicio rápido también deberá instalar la biblioteca cliente del SDK de Azure SDK para Azure Identity:For this quickstart, you'll also need to install the Azure SDK client library for Azure Identity:
dotnet add package Azure.Identity
Establecimiento de variables de entornoSet environment variables
Esta aplicación también usa el nombre del almacén de claves como variable de entorno llamada KEY_VAULT_NAME
.This application is using key vault name as an environment variable called KEY_VAULT_NAME
.
WindowsWindows
set KEY_VAULT_NAME=<your-key-vault-name>
Windows PowerShellWindows PowerShell
$Env:KEY_VAULT_NAME="<your-key-vault-name>"
macOS o LinuxmacOS or Linux
export KEY_VAULT_NAME=<your-key-vault-name>
Modelo de objetosObject model
La biblioteca cliente de certificados de Azure Key Vault para .NET permite administrar los certificados.The Azure Key Vault certificate client library for .NET allows you to manage certificates. En la sección Ejemplos de código se muestra cómo crear un cliente y establecer, recuperar y eliminar un certificado.The Code examples section shows how to create a client, set a certificate, retrieve a certificate, and delete a certificate.
Ejemplos de códigoCode examples
Adición de directivasAdd directives
Agregue las directivas siguientes al principio de Program.cs:Add the following directives to the top of Program.cs:
using System;
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
Autenticación y creación de un clienteAuthenticate and create a client
En este inicio rápido se emplea el usuario que ha iniciado sesión para autenticarlo en el almacén de claves, que es el método preferido para el desarrollo local.In this quickstart, logged in user is used to authenticate to key vault, which is preferred method for local development. Para las aplicaciones implementadas en Azure, la identidad administrada debe asignarse a App Service o la máquina virtual. Para más información, consulte Introducción a la identidad administrada.For applications deployed to Azure, managed identity should be assigned to App Service or Virtual Machine, for more information, see Managed Identity Overview.
En el ejemplo siguiente, el nombre del almacén de claves se expande al URI del almacén de claves, con el formato "https://<your-key-vault-name>.vault.azure.net".In below example, the name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.net". En este ejemplo se usa la clase "DefaultAzureCredential()" de la biblioteca de identidades de Azure, que permite usar el mismo código en entornos diferentes con distintas opciones para proporcionar la identidad.This example is using 'DefaultAzureCredential()' class from Azure Identity Library, which allows to use the same code across different environments with different options to provide identity. Para más información sobre la autenticación en el almacén de claves, consulte la Guía del desarrollador.For more information about authenticating to key vault, see Developer's Guide.
string keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = "https://" + keyVaultName + ".vault.azure.net";
var client = new CertificateClient(new Uri(kvUri), new DefaultAzureCredential());
Guardar certificadoSave a certificate
En este ejemplo, para simplificar, puede usar un certificado autofirmado con la directiva de emisión predeterminada.In this example, for simplicity you can use self-signed certificate with default issuance policy. Para esta tarea, use el método StartCreateCertificateAsync.For this task, use the StartCreateCertificateAsync method. Los parámetros del método aceptan un nombre de certificado y la directiva de certificados.The method's parameters accepts a certificate name and the certificate policy.
var operation = await client.StartCreateCertificateAsync("myCertificate", CertificatePolicy.Default);
var certificate = await operation.WaitForCompletionAsync();
Nota
Si el nombre del certificado existe, el código anterior creará una versión de ese certificado.If certificate name exists, above code will create new version of that certificate.
Recuperación de un certificadoRetrieve a certificate
Ahora puede recuperar el certificado creado anteriormente con el método GetCertificateAsync.You can now retrieve the previously created certificate with the GetCertificateAsync method.
var certificate = await client.GetCertificateAsync("myCertificate");
Eliminación de un certificadoDelete a certificate
Por último, vamos a eliminar y purgar el certificado desde el almacén de claves con los métodos StartDeleteCertificateAsync y PurgeDeletedCertificateAsync.Finally, let's delete and purge the certificate from your key vault with the StartDeleteCertificateAsync and PurgeDeletedCertificateAsync methods.
var operation = await client.StartDeleteCertificateAsync("myCertificate");
// You only need to wait for completion if you want to purge or recover the certificate.
await operation.WaitForCompletionAsync();
var certificate = operation.Value;
await client.PurgeDeletedCertificateAsync("myCertificate");
Código de ejemploSample code
Modifique la aplicación de consola de .NET Core para interactuar con el almacén de claves; para ello, complete los pasos siguientes:Modify the .NET Core console app to interact with the Key Vault by completing the following steps:
Reemplace el código de Program.cs por el código siguiente:Replace the code in Program.cs with the following code:
using System; using System.Threading.Tasks; using Azure.Identity; using Azure.Security.KeyVault.Certificates; namespace key_vault_console_app { class Program { static async Task Main(string[] args) { const string certificateName = "myCertificate"; var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME"); var kvUri = $"https://{keyVaultName}.vault.azure.net"; var client = new CertificateClient(new Uri(kvUri), new DefaultAzureCredential()); Console.Write($"Creating a certificate in {keyVaultName} called '{certificateName}' ..."); CertificateOperation operation = await client.StartCreateCertificateAsync(certificateName, CertificatePolicy.Default); await operation.WaitForCompletionAsync(); Console.WriteLine(" done."); Console.WriteLine($"Retrieving your certificate from {keyVaultName}."); var certificate = await client.GetCertificateAsync(certificateName); Console.WriteLine($"Your certificate version is '{certificate.Value.Properties.Version}'."); Console.Write($"Deleting your certificate from {keyVaultName} ..."); DeleteCertificateOperation deleteOperation = await client.StartDeleteCertificateAsync(certificateName); // You only need to wait for completion if you want to purge or recover the certificate. await deleteOperation.WaitForCompletionAsync(); Console.WriteLine(" done."); Console.Write($"Purging your certificate from {keyVaultName} ..."); await client.PurgeDeletedCertificateAsync(certificateName); Console.WriteLine(" done."); } } }
Prueba y comprobaciónTest and verify
Ejecute el siguiente comando para compilar el proyecto.Execute the following command to build the project
dotnet build
Aparece una variación del resultado siguiente:A variation of the following output appears:
Creating a certificate in mykeyvault called 'myCertificate' ... done.
Retrieving your certificate from mykeyvault.
Your certificate version is '8532359bced24e4bb2525f2d2050738a'.
Deleting your certificate from mykeyvault ... done
Purging your certificate from mykeyvault ... done
Pasos siguientesNext steps
En este inicio rápido, ha creado un almacén de claves, ha almacenado un certificado y, posteriormente, lo ha recuperado.In this quickstart, you created a key vault, stored a certificate, and retrieved that certificate.
Para más información sobre Key Vault y cómo integrarlo con las aplicaciones, consulte los artículos siguientes:To learn more about Key Vault and how to integrate it with your apps, see the following articles:
- Lea una introducción a Azure Key Vault.Read an Overview of Azure Key Vault
- Lea una introducción a los certificados.Read an Overview of certificates
- Vea un Tutorial sobre el acceso a Key Vault desde una aplicación de App Service.See an Access Key Vault from App Service Application Tutorial
- Consulte un Tutorial sobre el acceso a Key Vault desde una máquina virtual.See an Access Key Vault from Virtual Machine Tutorial
- Consulte la guía del desarrollador de Azure Key Vault.See the Azure Key Vault developer's guide
- Consulte Introducción a la seguridad de Azure Key VaultReview the Key Vault security overview