NodeJS 在请求中使用来自 Azure Key Vault 的客户端证书

NodeJS use client certificate from Azure Key Vault in request

我正在尝试向需要客户端证书身份验证的 API 执行 post 请求。证书以 pfx 形式上传到 Azure Key Vault。

我可以使用 npm 模块 @azure/keyvault-certificates@azure/keyvault-secrets 从 Key Vault 检索证书(参考:https://github.com/Azure/azure-sdk-for-js/issues/7647#issuecomment-594935307

问题是我不确定如何从这里开始。我正在使用 axios 执行服务器端请求,并在自定义 httpsAgent 中附加证书,如下所示:

const { certPfx, passphrase, endpoint } = options
const headers = constructHeaders(options)

const axiosInst = axios.create({
    httpsAgent: new Agent({
        pfx: certPfx,
        // pfx: Buffer.from(certPfx) // Alternative using the `cer` property of the returned certificate
        passphrase // Set from env var (I've verified that this is correct)
    })
})

return axiosInst.post(endpoint, constructBody(), {
    headers
})

如果通过 keyvault-certificates 检索证书,certPfx 变量是 Uint8Array,如果使用 keyvault-secrets.

,则变量是 base64 字符串

问题是,无论我使用哪种组合,我都会收到错误 Error: wrong tag 并在尝试 post 请求时失败。我尝试过使用和不使用密码以及使用 cer Uint8Array 和 base64 版本,但似乎没有任何效果。

有人有使用 Azure Key Vault 中的客户端证书通过 node/typescript 发出 https 请求的小样本吗?

似乎对证书进行编码的正确方法是使用 base64 缓冲区并将证书作为秘密读取(参考:https://github.com/Azure/azure-sdk-for-js/issues/7647#issuecomment-594935307

因此,假设您有适当的 SecretClient 和 Key Vault,并保存了证书,您可以这样做:

import { DefaultAzureCredential } from "@azure/identity"
import { SecretClient } from "@azure/keyvault-secrets"
import axios from "axios"

// omitted setup of some variables for clarity

const credential = new DefaultAzureCredential()
const client = new SecretClient(vaultUrl, credential)
const secret = await client.getSecret(certName) // The secret name will be the same as the cert name
const certPfx = secret.value // assuming this is set.

const axiosResponse = await axios(endpoint, {
    data: constructBody(),
    headers,
    method: "POST",
    httpsAgent: new Agent({
        pfx: Buffer.from(certPfx, "base64"),
        passphrase: ""
    })
})