How to add a certificate to WebClient in Powershell

I will not study a web page that requires client-side authentication. How can I provide my certificate from Certstore to WebRquest: Is there a way to specify this in the credentials odr in the proxy?

$webclient = New-Object Net.WebClient # The next 5 lines are required if your network has a proxy server $webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials if($webclient.Proxy -ne $null) { $webclient.Proxy.Credentials = ` [System.Net.CredentialCache]::DefaultNetworkCredentials } # This is the main call $output = $webclient.DownloadString("$URL") 

PS: Maybe this helps: How can you add a certificate to WebClient (C #)? But I do not understand him. ;-)

+6
source share
1 answer

Using the new Add-Type functionality in PowerShell v2, you can create your own class, which you can then use to create a typical WebRequest. I have included the method in a custom class so that you can add certificates that can be used for authentication.

 PS C:\> $def = @" public class ClientCertWebClient : System.Net.WebClient { System.Net.HttpWebRequest request = null; System.Security.Cryptography.X509Certificates.X509CertificateCollection certificates = null; protected override System.Net.WebRequest GetWebRequest(System.Uri address) { request = (System.Net.HttpWebRequest)base.GetWebRequest(address); if (certificates != null) { request.ClientCertificates.AddRange(certificates); } return request; } public void AddCerts(System.Security.Cryptography.X509Certificates.X509Certificate[] certs) { if (certificates == null) { certificates = new System.Security.Cryptography.X509Certificates.X509CertificateCollection(); } if (request != null) { request.ClientCertificates.AddRange(certs); } certificates.AddRange(certs); } } "@ PS C:\> Add-Type -TypeDefinition $def 

You might want to limit the addition of certificates to only one (or one) that you want to use, and not just use every available certificate in the current user's store, but here is an example that just downloads all of them

 PS C:\> $wc = New-Object ClientCertWebClient PS C:\> $certs = dir cert:\CurrentUser\My PS C:\> $wc.AddCerts($certs) PS C:\> $wc.DownloadString("http://stackoverflow.com") 
+10
source

All Articles