1

Pretty new to PowerShell and hoping someone can point me in the right direction.

I need to perform a POST request and have to pass it a locally stored cert (x509) during the POST request, for authentication.

What is the best way or way to accomplish this? I've found plenty of example to be able to perform this task in .net/C# but I am not finding anything that will accomplish this task in PowerShell.

Here is my POST request code, again I would like to point to a cert stored locally "C:\code\cert.crt" and pass it during the web transaction.

$url = "https://myUrl/uploadTester"
$data = '{"data": "988309487577839444"}'
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$b = [System.Text.Encoding]::ASCII.GetBytes($data)
$web = [System.Net.WebRequest]::Create($url)
$web.Method = "POST"
$web.ContentLength = $b.Length
$web.ContentType = "application/x-www-form-urlencoded"
$stream = $web.GetRequestStream()
$stream.Write($b,0,$b.Length)
$stream.close()

$reader = New-Object System.IO.Streamreader -ArgumentList $web.GetResponse().GetResponseStream()
$reader.ReadToEnd()
$reader.Close()

Thanks for all the help in advanced.

user1048209
  • 181
  • 1
  • 5
  • 13

1 Answers1

0

It's pretty easy to convert C# to PowerShell. Give this a try:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile("C:\Users\Andy\Desktop\Test.cer")
$web = [System.Net.WebRequest]::Create($url)
$web.ClientCertificates.Add($Cert)

I adapted this from: http://support.microsoft.com/kb/895971

Looks like the key is the ClientCertificates property.

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.clientcertificates.aspx

Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • Thanks for the quick reply Andy. I do have one question: – user1048209 Apr 12 '12 at 12:42
  • Thanks for the quick reply Andy. I do have one question regarding the code. Do I still need to leave the the line "ServerCertificateValidationCallback = {$true}". Does this not ignore all certificate checks altogether? Or is the fact that I am providing a cert use the Create($url) taking care of the actual cert verification check? – user1048209 Apr 12 '12 at 14:32
  • @user1048209 I think ServerCertificateValidationCallback = {$true} is for server side certificate validation rather than client certificates sent to the server. – Andy Arismendi Apr 12 '12 at 18:54