JavaScript용 Azure Key Vault 인증서 클라이언트 라이브러리 - 버전 4.8.0

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

Azure Key Vault 대해 자세히 알아보려면 Azure Key Vault란?을 검토할 수 있습니다.

Node.js 애플리케이션에서 Azure Key Vault 인증서용 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • 인증서를 가져오기, 설정 및 삭제합니다.
  • 인증서, 해당 특성, 발급자, 정책, 작업 및 연락처를 업데이트합니다.
  • 인증서 백업 및 복원
  • 삭제된 인증서를 가져오기, 제거 또는 복구합니다.
  • 인증서의 모든 버전을 가져옵니다.
  • 모든 인증서를 가져옵니다.
  • 삭제된 인증서를 모두 가져옵니다.

참고: 이 패키지는 Azure Key Vault 서비스 제한으로 인해 브라우저에서 사용할 수 없습니다. 지침은 이 문서를 참조하세요.

주요 링크:

시작

현재 지원되는 환경

필수 구성 요소

패키지 설치

npm을 사용하여 Azure Key Vault 인증서 클라이언트 라이브러리 설치

npm install @azure/keyvault-certificates

ID 라이브러리 설치

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

npm install @azure/identity

TypeScript 구성

TypeScript 사용자는 노드 형식 정의를 설치해야 합니다.

npm install @types/node

또한 tsconfig.json 사용하도록 설정 compilerOptions.allowSyntheticDefaultImports 해야 합니다. 를 사용하도록 설정한 compilerOptions.esModuleInteropallowSyntheticDefaultImports 경우 는 기본적으로 사용하도록 설정됩니다. 자세한 내용은 TypeScript의 컴파일러 옵션 핸드북 을 참조하세요.

Azure Active Directory를 사용하여 인증

Key Vault 서비스는 Azure Active Directory를 사용하여 API에 대한 요청을 인증합니다. 패키지는 @azure/identity 애플리케이션에서 이 작업을 수행하는 데 사용할 수 있는 다양한 자격 증명 형식을 제공합니다. 에 대한 추가 정보는 시작하기 위한 @azure/identity 자세한 내용과 샘플을 제공합니다.

Azure Key Vault 서비스와 상호 작용하려면 클래스의 instanceCertificateClient, 자격 증명 모음 URL 및 자격 증명 개체를 만들어야 합니다. 이 문서에 표시된 예제에서는 라는 자격 증명 개체를 사용합니다. 이 개체 DefaultAzureCredential는 로컬 개발 및 프로덕션 환경을 비롯한 대부분의 시나리오에 적합합니다. 또한 프로덕션 환경에서 인증에 관리 ID 를 사용하는 것이 좋습니다.

다양한 인증 방법 및 해당 자격 증명 유형에 대한 자세한 내용은 Azure ID 설명서에서 확인할 수 있습니다.

다음은 빠른 예제입니다. 먼저 및 를 CertificateClient가져옵니다DefaultAzureCredential.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

이러한 키를 가져오면 다음으로 키 자격 증명 모음 서비스에 연결할 수 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

// Build the URL to reach your key vault
const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

// Lastly, create our certificates client and connect to the service
const client = new CertificateClient(url, credential);

주요 개념

  • 인증서 클라이언트는 JavaScript 애플리케이션에서 Azure Key Vault API의 인증서와 관련된 API 메서드와 상호 작용하는 기본 인터페이스입니다. 초기화되면 인증서를 만들고, 읽고, 업데이트하고, 삭제하는 데 사용할 수 있는 기본 메서드 집합을 제공합니다.
  • 인증서 버전은 Key Vault 인증서의 버전입니다. 사용자가 고유한 인증서 이름에 값을 할당할 때마다 해당 인증서의 새 버전 이 만들어집니다. 특정 버전이 쿼리에 제공되지 않는 한 이름으로 인증서를 검색하면 항상 할당된 최신 값이 반환됩니다.
  • 일시 삭제 를 사용하면 Key Vault가 삭제 및 제거를 두 개의 개별 단계로 지원할 수 있으므로 삭제된 인증서는 즉시 손실되지 않습니다. 이는 Key Vault 일시 삭제를 사용하도록 설정한 경우에만 발생합니다.
  • 생성된 인증서에서 인증서 백업을 생성할 수 있습니다. 이러한 백업은 이진 데이터로 제공되며 이전에 삭제된 인증서를 다시 생성하는 데만 사용할 수 있습니다.

Azure Key Vault 서비스 API 버전 지정

기본적으로 이 패키지는 최신 Azure Key Vault 서비스 버전()을 7.1사용합니다. 지원되는 유일한 다른 버전은 입니다 7.0. 아래와 같이 클라이언트 생성자에서 옵션을 serviceVersion 설정하여 사용 중인 서비스 버전을 변경할 수 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

// Change the Azure Key Vault service API version being used via the `serviceVersion` option
const client = new CertificateClient(url, credential, {
  serviceVersion: "7.0",
});

예제

다음 섹션에서는 Azure Key Vault 인증서를 사용하는 몇 가지 일반적인 작업을 다루는 코드 조각을 제공합니다. 여기서 다루는 시나리오는 다음으로 구성됩니다.

인증서 만들기 및 설정

beginCreateCertificate는 Azure Key Vault 저장할 인증서를 만듭니다. 이름이 같은 인증서가 이미 있는 경우 새 버전의 인증서가 만들어집니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  // Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
  await client.beginCreateCertificate(certificateName, {
    issuerName: "Self",
    subject: "cn=MyCert",
  });
}

main();

인증서 이름 및 정책 외에도 선택적 값을 사용하여 세 번째 인수에 다음 속성을 전달할 수도 있습니다.

  • enabled: 인증서를 사용할 수 있는지 여부를 결정하는 부울 값입니다.
  • tags: 인증서를 검색하고 필터링하는 데 사용할 수 있는 키-값 집합입니다.
const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

// Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};
const enabled = true;
const tags = {
  myCustomTag: "myCustomTagsValue",
};

async function main() {
  await client.beginCreateCertificate(certificateName, certificatePolicy, {
    enabled,
    tags,
  });
}

main();

동일한 이름으로 를 beginCreateCertificate 호출하면 동일한 인증서의 새 버전이 만들어지며, 이 인증서에는 제공된 최신 특성이 포함됩니다.

인증서를 완전히 만드는 beginCreateCertificate 데 시간이 걸리기 때문에 지침에 따라 기본 장기 실행 작업을 추적하는 폴러 개체를 반환합니다. https://azure.github.io/azure-sdk/typescript_design.html#ts-lro

수신된 폴러를 사용하면 를 호출하여 만든 인증서를 가져올 수 있습니다 poller.getResult(). 인증서를 만들 때까지 개별 서비스 호출을 실행하거나 프로세스가 완료될 때까지 대기하여 삭제가 완료될 때까지 기다릴 수도 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};

async function main() {
  const poller = await client.beginCreateCertificate(certificateName, certificatePolicy);

  // You can use the pending certificate immediately:
  const pendingCertificate = poller.getResult();

  // Or you can wait until the certificate finishes being signed:
  const keyVaultCertificate = await poller.pollUntilDone();
  console.log(keyVaultCertificate);
}

main();

인증서가 서명될 때까지 대기하는 또 다른 방법은 다음과 같이 개별 호출을 수행하는 것입니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");
const { delay } = require("@azure/core-util");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";
const certificatePolicy = {
  issuerName: "Self",
  subject: "cn=MyCert",
};

async function main() {
  const poller = await client.beginCreateCertificate(certificateName, certificatePolicy);

  while (!poller.isDone()) {
    await poller.poll();
    await delay(5000);
  }

  console.log(`The certificate ${certificateName} is fully created`);
}

main();

Key Vault 인증서 가져오기

자격 증명 모음에서 인증서를 다시 읽는 가장 간단한 방법은 이름으로 인증서를 가져오는 것입니다. getCertificate 는 인증서의 정책과 함께 최신 버전의 인증서를 검색합니다. 필요에 따라 버전을 지정하는 경우 를 호출 getCertificateVersion 하여 다른 버전의 인증서를 가져올 수 있습니다. getCertificateVersion 는 인증서의 정책을 반환하지 않습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const latestCertificate = await client.getCertificate(certificateName);
  console.log(`Latest version of the certificate ${certificateName}: `, latestCertificate);
  const specificCertificate = await client.getCertificateVersion(
    certificateName,
    latestCertificate.properties.version
  );
  console.log(
    `The certificate ${certificateName} at the version ${latestCertificate.properties.version}: `,
    specificCertificate
  );
}

main();

인증서의 전체 정보 가져오기

Azure Key Vault 디자인은 키, 비밀 및 인증서를 명확하게 구분합니다. Key Vault 서비스의 인증서 기능은 키 및 비밀 기능을 사용하도록 설계되었습니다. Key Vault 인증서의 컴퍼지션을 평가해 보겠습니다.

Key Vault 인증서가 만들어지면 주소 지정 가능한 키와 암호도 동일한 이름으로 만들어집니다. Key Vault 키는 키 작업을 허용하고, Key Vault 비밀은 인증서 값을 비밀로 검색할 수 있게 합니다. Key Vault 인증서에는 공용 x509 인증서 메타데이터도 포함됩니다. 원본: 인증서의 컴퍼지션입니다.

프라이빗 키가 공용 인증서가 포함된 Key Vault 비밀에 저장된다는 것을 알면 Key Vault Secrets 클라이언트를 사용하여 검색할 수 있습니다.

// Using the same credential object we used before,
// and the same keyVaultUrl,
// let's create a SecretClient
import { SecretClient } from "@azure/keyvault-secrets";

const secretClient = new SecretClient(keyVaultUrl, credential);

// Assuming you've already created a Key Vault certificate,
// and that certificateName contains the name of your certificate
const certificateSecret = await secretClient.getSecret(certificateName);

// Here we can find both the private key and the public certificate, in PKCS 12 format:
const PKCS12Certificate = certificateSecret.value!;

// You can write this into a file:
fs.writeFileSync("myCertificate.p12", PKCS12Certificate);

기본적으로 인증서의 콘텐츠 형식은 PKCS 12입니다. 인증서의 콘텐츠 형식을 지정하면 PEM 형식으로 검색할 수 있습니다. PEM 인증서를 만드는 방법을 표시하기 전에 먼저 PKCS 12 인증서에서 PEM 비밀 키를 검색하는 방법을 살펴보겠습니다.

를 사용하면 openssl다음 명령을 사용하여 PEM 형식으로 공용 인증서를 검색할 수 있습니다.

openssl pkcs12 -in myCertificate.p12 -out myCertificate.crt.pem -clcerts -nokeys

를 사용하여 openssl 다음과 같이 프라이빗 키를 검색할 수도 있습니다.

openssl pkcs12 -in myCertificate.p12 -out myCertificate.key.pem -nocerts -nodes

두 경우 모두 openssl은 인증서를 만드는 데 사용되는 암호를 요청합니다. 지금까지 사용한 샘플 코드는 암호를 지정하지 않았으므로 각 명령의 끝에 추가할 -passin 'pass:' 수 있습니다.

PEM 형식의 인증서

인증서를 PEM 형식으로 작업하려는 경우 인증서를 만들 때 속성을 제공하여 contentType 인증서를 PEM 형식으로 만들고 관리하도록 Azure의 Key Vault 서비스에 지시할 수 있습니다.

다음 예제에서는 인증서 및 비밀에 대한 Key Vault 클라이언트를 사용하여 PEM 형식 인증서의 공용 및 프라이빗 부분을 만들고 검색하는 방법을 보여 줍니다.

// Creating the certificate
const certificateName = "MyCertificate";
const createPoller = await client.beginCreateCertificate(certificateName, {
  issuerName: "Self",
  subject: "cn=MyCert",
  contentType: "application/x-pem-file", // Here you specify you want to work with PEM certificates.
});
const keyVaultCertificate = await createPoller.pollUntilDone();

// Getting the PEM formatted private key and public certificate:
const certificateSecret = await secretClient.getSecret(certificateName);
const PEMPair = certificateSecret.value!;

console.log(PEMPair);

공용 인증서는 프라이빗 키와 동일한 콘텐츠 Blob에 있습니다. PEM 헤더를 사용하여 그에 따라 추출할 수 있습니다.

모든 인증서 나열

listPropertiesOfCertificates는 Key Vault 모든 인증서를 나열합니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

async function main() {
  for await (let certificateProperties of client.listPropertiesOfCertificates()) {
    console.log("Certificate properties: ", certificateProperties);
  }
}

main();

인증서 업데이트

인증서 특성은 다음과 같이 를 사용하여 기존 인증서 버전으로 updateCertificate업데이트할 수 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const result = await client.getCertificate(certificateName);
  await client.updateCertificateProperties(certificateName, result.properties.version, {
    enabled: false,
    tags: {
      myCustomTag: "myCustomTagsValue",
    },
  });
}

main();

인증서의 정책은 다음과 같이 를 사용하여 updateCertificatePolicy개별적으로 업데이트할 수도 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const result = client.getCertificate(certificateName);
  // Note: Sending `Self` as the `issuerName` of the certificate's policy will create a self-signed certificate.
  await client.updateCertificatePolicy(certificateName, {
    issuerName: "Self",
    subject: "cn=MyCert",
  });
}

main();

인증서 삭제

메서드는 beginDeleteCertificate 삭제할 인증서를 설정합니다. 이 프로세스는 필요한 리소스를 사용할 수 있는 즉시 백그라운드에서 발생합니다.

Key Vault 일시 삭제를 사용하도록 설정한 경우 이 작업은 인증서에 삭제된 인증서로만 레이블을 지정합니다. 삭제된 인증서는 업데이트할 수 없습니다. 읽기, 복구 또는 제거만 가능합니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  const poller = await client.beginDeleteCertificate(certificateName);

  // You can use the deleted certificate immediately:
  const deletedCertificate = poller.getResult();

  // The certificate is being deleted. Only wait for it if you want to restore it or purge it.
  await poller.pollUntilDone();

  // You can also get the deleted certificate this way:
  await client.getDeletedCertificate(certificateName);

  // Deleted certificates can also be recovered or purged.

  // recoverDeletedCertificate returns a poller, just like beginDeleteCertificate.
  // const recoverPoller = await client.beginRecoverDeletedCertificate(certificateName);
  // await recoverPoller.pollUntilDone();

  // If a certificate is done and the Key Vault has soft-delete enabled, the certificate can be purged with:
  await client.purgeDeletedCertificate(certificateName);
}

main();

인증서 삭제는 즉시 수행되지 않으므로 삭제된 인증서를 읽거나 복구하거나 제거할 수 있기 전에 메서드가 호출된 후 beginDeleteCertificate 약간의 시간이 필요합니다.

인증서 목록 반복

CertificateClient를 사용하면 인증서 자격 증명 모음의 모든 인증서뿐만 아니라 삭제된 모든 인증서 및 특정 인증서 버전을 통해 검색하고 반복할 수 있습니다. 다음 API 메서드를 사용할 수 있습니다.

  • listPropertiesOfCertificates 는 삭제되지 않은 모든 인증서를 최신 버전에서만 이름으로 나열합니다.
  • listDeletedCertificates 는 삭제된 모든 인증서를 최신 버전에서만 해당 이름으로 나열합니다.
  • listPropertiesOfCertificateVersions 는 인증서 이름을 기반으로 하는 인증서의 모든 버전을 나열합니다.

다음과 같이 사용할 수 있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  for await (let certificateProperties of client.listPropertiesOfCertificates()) {
    console.log("Certificate properties: ", certificateProperties);
  }
  for await (let deletedCertificate of client.listDeletedCertificates()) {
    console.log("Deleted certificate: ", deletedCertificate);
  }
  for await (let certificateProperties of client.listPropertiesOfCertificateVersions(
    certificateName
  )) {
    console.log("Certificate properties: ", certificateProperties);
  }
}

main();

이러한 모든 메서드는 사용 가능한 모든 결과를 한 번에 반환합니다. 페이지별로 검색하려면 다음과 같이 사용하려는 API 메서드를 호출한 직후에 를 추가 .byPage() 합니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { CertificateClient } = require("@azure/keyvault-certificates");

const credential = new DefaultAzureCredential();

const vaultName = "<YOUR KEYVAULT NAME>";
const url = `https://${vaultName}.vault.azure.net`;

const client = new CertificateClient(url, credential);

const certificateName = "MyCertificateName";

async function main() {
  for await (let page of client.listPropertiesOfCertificates().byPage()) {
    for (let certificateProperties of page) {
      console.log("Certificate properties: ", certificateProperties);
    }
  }
  for await (let page of client.listDeletedCertificates().byPage()) {
    for (let deletedCertificate of page) {
      console.log("Deleted certificate: ", deletedCertificate);
    }
  }
  for await (let page of client.listPropertiesOfCertificateVersions(certificateName).byPage()) {
    for (let certificateProperties of page) {
      console.log("Properties of certificate: ", certificateProperties);
    }
  }
}

main();

문제 해결

로깅을 사용하도록 설정하면 실패에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info로 설정합니다. 또는 @azure/logger에서 setLogLevel을 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

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

다음 단계

다음 링크를 통해 더 많은 코드 샘플을 찾을 수 있습니다.

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions