如何在PowerShell中为WebClient添加证书

6

我想检查一个需要客户端证书认证的网页。我该如何从证书存储中提供我的证书给Web请求?是否可以在凭据或代理中指定此项?

$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:也许这个链接能帮到你:如何在WebClient (C#)中添加证书? 但是我不太懂...;-)


这个 SO 问题的意思是你要么直接使用 HttpWebRequest,要么重写 WebClient 以便添加证书。 - JasonMArcher
1个回答

11

使用 PowerShell v2 中新增的 Add-Type 功能,您可以创建一个自定义类,用于发出常规的 WebRequest。我已经在自定义类中包含了一个方法,允许您添加可用于身份验证的证书。

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

你或许想要限制添加的证书只有你想使用的一个或多个,而不是使用当前用户存储中的所有可用证书,但这里给出一个示例,它会加载所有可用证书:

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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接