다음을 통해 공유


.NET용 Azure Key Vault 인증서 클라이언트 라이브러리 - 버전 4.5.1

Azure Key Vault 클라우드 애플리케이션 전체에서 사용되는 인증서의 보안 스토리지 및 자동화된 관리를 제공하는 클라우드 서비스입니다. 여러 인증서와 동일한 인증서의 여러 버전을 Azure Key Vault 유지할 수 있습니다. 자격 증명 모음의 각 인증서에는 인증서 발급 및 수명을 제어하는 정책과 만료가 임박한 인증서로 수행할 작업이 있습니다.

Azure Key Vault 인증서 클라이언트 라이브러리를 사용하면 프로그래밍 방식으로 인증서를 관리할 수 있으며 인증서, 정책, 발급자 및 연락처를 만들고, 업데이트하고, 나열하고, 삭제하는 방법을 제공합니다. 라이브러리는 보류 중인 인증서 작업 관리 및 삭제된 인증서 관리도 지원합니다.

소스 코드 | 패키지(NuGet) | API 참조 설명서 | 제품 설명서 | 샘플 | 마이그레이션 가이드

시작

패키지 설치

NuGet을 사용하여 .NET용 Azure Key Vault 인증서 클라이언트 라이브러리를 설치합니다.

dotnet add package Azure.Security.KeyVault.Certificates

필수 구성 요소

  • Azure 구독.
  • 기존 Azure Key Vault. Azure Key Vault 만들어야 하는 경우 Azure Portal 또는 Azure CLI를 사용할 수 있습니다.
  • RBAC(권장) 또는 액세스 제어를 사용하여 기존 Azure Key Vault 권한 부여

Azure CLI를 사용하는 경우 및 <your-key-vault-name> 을 고유한 고유한 이름으로 바꿉 <your-resource-group-name> 니다.

az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>

클라이언트 인증

Azure Key Vault 서비스와 상호 작용하려면 CertificateClient 클래스의 instance 만들어야 합니다. 포털에서 "DNS 이름"으로 표시할 수 있는 자격 증명 모음 URL과 클라이언트 개체를 인스턴스화하기 위한 자격 증명이 필요합니다.

아래에 표시된 예제에서는 로컬 개발 및 프로덕션 환경을 비롯한 대부분의 시나리오에 적합한 를 사용합니다 DefaultAzureCredential. 또한 프로덕션 환경에서 인증에 관리 ID를 사용하는 것이 좋습니다. Azure ID 설명서에서 다양한 인증 방법 및 해당 자격 증명 형식에 대한 자세한 정보를 찾을 수 있습니다.

아래에 표시된 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용 DefaultAzureCredential 하려면 먼저 Azure.Identity 패키지를 설치해야 합니다.

dotnet add package Azure.Identity

CertificateClient 만들기

를 인스턴스화 DefaultAzureCredential 하여 클라이언트에 전달합니다. 동일한 ID로 인증하는 경우 토큰 자격 증명의 동일한 instance 여러 클라이언트에서 사용할 수 있습니다.

// Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
// including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
var client = new CertificateClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

주요 개념

KeyVaultCertificate

A KeyVaultCertificate 는 Azure Key Vault 내의 기본 리소스입니다. 인증서를 사용하여 암호화되거나 서명된 데이터를 암호화하고 확인합니다.

CertificateClient

CertificateClient 사용하여 자격 증명 모음에서 인증서를 가져와 새 인증서 및 새 버전의 기존 인증서를 만들고, 인증서 메타데이터를 업데이트하고, 인증서를 삭제할 수 있습니다. 인증서 발급자, 연락처 및 인증서의 관리 정책을 관리할 수도 있습니다. 아래 예제에 나와 있습니다.

스레드로부터의 안전성

모든 클라이언트 instance 메서드는 스레드로부터 안전하고 서로 독립적임을 보장합니다(지침). 이렇게 하면 스레드 간에 클라이언트 인스턴스를 다시 사용하는 것이 항상 안전합니다.

추가 개념

클라이언트 옵션 | 응답 | 에 액세스 장기 실행 작업 | 오류 | 처리 진단 | 조롱 | 클라이언트 수명

예제

Azure.Security.KeyVault.Certificates 패키지는 동기 및 비동기 API를 지원합니다.

다음 섹션에서는 위에서 만든 를 사용하여 client 가장 일반적인 Azure Key Vault 인증서 서비스 관련 작업을 다루는 여러 코드 조각을 제공합니다.

동기화 예제

비동기 예제

인증서 만들기

StartCreateCertificate는 Azure Key Vault 저장할 인증서를 만듭니다. 이름이 같은 인증서가 이미 있는 경우 새 버전의 인증서가 만들어집니다. 인증서를 만들 때 사용자는 인증서 수명을 제어하는 정책을 지정할 수 있습니다. 정책이 지정되지 않은 경우 기본 정책이 사용됩니다. 작업은 StartCreateCertificate 를 반환합니다 CertificateOperation. 다음 예제에서는 기본 정책을 사용하여 자체 서명된 인증서를 만듭니다.

// Create a certificate. This starts a long running operation to create and sign the certificate.
CertificateOperation operation = client.StartCreateCertificate("MyCertificate", CertificatePolicy.Default);

// You can await the completion of the create certificate operation.
// You should run UpdateStatus in another thread or do other work like pumping messages between calls.
while (!operation.HasCompleted)
{
    Thread.Sleep(2000);

    operation.UpdateStatus();
}

KeyVaultCertificateWithPolicy certificate = operation.Value;

참고: 인증서 발급자 및 유효성 검사 방법에 따라 인증서 만들기 및 서명에는 확정되지 않은 시간이 걸릴 수 있습니다. 사용자는 자체 서명된 인증서 또는 잘 알려진 응답 시간이 있는 발급자와 같이 애플리케이션의 scope 작업이 합리적으로 완료될 수 있는 경우에만 인증서 작업을 기다려야 합니다.

인증서 검색

GetCertificate는 와 함께 Azure Key Vault 저장된 최신 버전의 인증서를 검색합니다CertificatePolicy.

KeyVaultCertificateWithPolicy certificateWithPolicy = client.GetCertificate("MyCertificate");

GetCertificateVersion 는 자격 증명 모음에서 특정 버전의 인증서를 검색합니다.

KeyVaultCertificate certificate = client.GetCertificateVersion(certificateWithPolicy.Name, certificateWithPolicy.Properties.Version);

기존 인증서 업데이트

UpdateCertificate는 Azure Key Vault 저장된 인증서를 업데이트합니다.

CertificateProperties certificateProperties = new CertificateProperties(certificate.Id);
certificateProperties.Tags["key1"] = "value1";

KeyVaultCertificate updated = client.UpdateCertificateProperties(certificateProperties);

인증서 나열

GetCertificates 인증서의 선택 속성을 반환하여 자격 증명 모음의 인증서를 열거합니다. 인증서의 중요한 필드는 반환되지 않습니다. 이 작업을 수행하려면 인증서/목록 권한이 필요합니다.

Pageable<CertificateProperties> allCertificates = client.GetPropertiesOfCertificates();

foreach (CertificateProperties certificateProperties in allCertificates)
{
    Console.WriteLine(certificateProperties.Name);
}

인증서 삭제

DeleteCertificate는 Azure Key Vault 저장된 인증서의 모든 버전을 삭제합니다. Azure Key Vault 일시 삭제를 사용하도록 설정하지 않으면 이 작업은 인증서를 영구적으로 삭제합니다. 일시 삭제를 사용하도록 설정하면 인증서가 삭제되도록 표시되며 예약된 제거 날짜까지 선택적으로 제거하거나 복구할 수 있습니다.

DeleteCertificateOperation operation = client.StartDeleteCertificate("MyCertificate");

// You only need to wait for completion if you want to purge or recover the certificate.
// You should call `UpdateStatus` in another thread or after doing additional work like pumping messages.
while (!operation.HasCompleted)
{
    Thread.Sleep(2000);

    operation.UpdateStatus();
}

DeletedCertificate certificate = operation.Value;
client.PurgeDeletedCertificate(certificate.Name);

비동기적으로 인증서 만들기

비동기 API는 동기 API와 동일하지만 비동기 메서드에 대한 일반적인 "비동기" 접미사와 함께 반환하고 를 Task반환합니다.

이 예제에서는 지정된 선택적 인수를 사용하여 Azure Key Vault 인증서를 만듭니다.

// Create a certificate. This starts a long running operation to create and sign the certificate.
CertificateOperation operation = await client.StartCreateCertificateAsync("MyCertificate", CertificatePolicy.Default);

// You can await the completion of the create certificate operation.
KeyVaultCertificateWithPolicy certificate = await operation.WaitForCompletionAsync();

비동기적으로 인증서 나열

인증서 나열은 메서드 대기에 GetPropertiesOfCertificatesAsync 의존하지 않지만 문과 함께 사용할 수 있는 을 await foreach 반환 AsyncPageable<CertificateProperties> 합니다.

AsyncPageable<CertificateProperties> allCertificates = client.GetPropertiesOfCertificatesAsync();

await foreach (CertificateProperties certificateProperties in allCertificates)
{
    Console.WriteLine(certificateProperties.Name);
}

비동기적으로 인증서 삭제

인증서를 제거하기 전에 비동기적으로 삭제하는 경우 작업에서 메서드를 대기할 WaitForCompletionAsync 수 있습니다. 기본적으로 이 루프는 무기한 반복되지만 를 전달 CancellationToken하여 취소할 수 있습니다.

DeleteCertificateOperation operation = await client.StartDeleteCertificateAsync("MyCertificate");

// You only need to wait for completion if you want to purge or recover the certificate.
await operation.WaitForCompletionAsync();

DeletedCertificate certificate = operation.Value;
await client.PurgeDeletedCertificateAsync(certificate.Name);

문제 해결

다양한 오류 시나리오를 진단하는 방법에 대한 자세한 내용은 문제 해결 가이드 를 참조하세요.

일반

.NET SDK를 사용하여 Azure Key Vault 인증서 클라이언트 라이브러리와 상호 작용하는 경우 서비스에서 반환되는 오류는 REST API 요청에 대해 반환된 동일한 HTTP 상태 코드에 해당합니다.

예를 들어 Azure Key Vault 404 존재하지 않는 키를 검색하려고 하면 를 나타내는 Not Found오류가 반환됩니다.

try
{
    KeyVaultCertificateWithPolicy certificateWithPolicy = client.GetCertificate("SomeCertificate");
}
catch (RequestFailedException ex)
{
    Console.WriteLine(ex.ToString());
}

작업의 클라이언트 요청 ID와 같은 추가 정보가 기록됩니다.

Message:
    Azure.RequestFailedException : Service request failed.
    Status: 404 (Not Found)
Content:
    {"error":{"code":"CertificateNotFound","message":"Certificate not found: MyCertificate"}}

Headers:
    Cache-Control: no-cache
    Pragma: no-cache
    Server: Microsoft-IIS/10.0
    x-ms-keyvault-region: westus
    x-ms-request-id: 625f870e-10ea-41e5-8380-282e5cf768f2
    x-ms-keyvault-service-version: 1.1.0.866
    x-ms-keyvault-network-info: addr=131.107.174.199;act_addr_fam=InterNetwork;
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Strict-Transport-Security: max-age=31536000;includeSubDomains
    X-Content-Type-Options: nosniff
    Date: Tue, 18 Jun 2019 16:02:11 GMT
    Content-Length: 75
    Content-Type: application/json; charset=utf-8
    Expires: -1

다음 단계

이 GitHub 리포지토리에서 여러 Azure Key Vault 인증서 클라이언트 라이브러리 샘플을 사용할 수 있습니다. 이러한 샘플은 Azure Key Vault 작업하는 동안 일반적으로 발생하는 추가 시나리오에 대한 예제 코드를 제공합니다.

  • Sample1_HelloWorld.md - 다음을 포함하여 Azure Key Vault 인증서를 사용하기 위한 것입니다.

    • 인증서 만들기
    • 기존 인증서 가져오기
    • 기존 인증서 업데이트
    • 인증서 삭제
  • Sample2_GetCertificates.md - 다음을 포함하여 Azure Key Vault 인증서를 사용하기 위한 예제 코드입니다.

    • 인증서 만들기
    • Key Vault 모든 인증서 나열
    • 지정된 인증서의 버전 나열
    • Key Vault 인증서 삭제
    • Key Vault 삭제된 인증서 나열

추가 설명서

참여

이러한 라이브러리를 빌드, 테스트 및 기여하는 방법에 대한 자세한 내용은 CONTRIBUTING.md 참조하세요.

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 https://cla.microsoft.com 을 참조하세요.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.

Impressions