0

I have an Azure KeyVault that holds a .pfx-Client Certificate that I need in order to authenticate a WebRequest sent from an Azure Function to a third party Web Service.

When I conduct this WebRequest from my local machine using the following code (and loading the .pfx Certificate from my local drive) everything works perfectly fine:

$certPath = 'C:\Users\abc\certificates\cert.pfx'
$certPassword = "1234567890"

$URI = 'https://example.com/api'

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath, $certPassword)

$request = [System.Net.WebRequest]::Create($URI)
$request.Method = "GET"
$request.ClientCertificates.Add($cert)

$response = $request.GetResponse()
$responseStream = $response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($responseStream)
$responseContent = $reader.ReadToEnd()

$reader.Close()
$responseStream.Close()
$response.Close()

$responseContent

However when fetching the Certificate + its password from the Azure KeyVault using

$certificatePassword = Get-AzKeyVaultSecret -VaultName $env:KeyVaultName -Name $env:PasswordLabel
$certificatePasswordString = $certificatePassword.SecretValue
$certificate = Get-AzKeyVaultCertificate -VaultName $env:KeyVaultName -Name $env:CertificateLabel

And then try to create the $cert object just like above

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certificate, $certificatePassword)

I just can't get it to work... How do I create the $cert object using a Certificate from an Azure KeyVault?

I also tried to convert the certificate to another format using

$certBytes = [System.Convert]::FromBase64String($certificate.Certificate)

And to pass $certBytes instead of the $certificate object but it wouldn't work either.

Does anyone have experience with using Azure KeyVault Certificates for Client Authentication using Powershell?

I am grateful for any kind of help - thank you in advance!

ABF
  • 57
  • 9
  • 1
    The problem is that when you get the certificate, as a certificate, you only get its public key, to get the full with private key, then you need to get it as a secret. https://learn.microsoft.com/en-us/powershell/module/az.keyvault/get-azkeyvaultsecret?view=azps-9.7.1 – Tore Nestenius May 23 '23 at 16:11

0 Answers0