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!