【问题标题】:How can you add a Certificate to WebClient in Powershell如何在 Powershell 中向 WebClient 添加证书
【发布时间】:2011-08-03 01:52:53
【问题描述】:

我不想检查需要客户端证书身份验证的网页。 如何将我的证书从 Certstore 提供给 Webrequest: 有没有办法在代理中的 Credentials odr 中指定这一点?

$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:也许这有帮助:How can you add a Certificate to WebClient (C#)? 但我不明白.. ;-)

【问题讨论】:

  • 这个 SO 问题的意思是您要么必须直接使用 HttpWebRequest,要么覆盖 WebClient 以便添加证书。

标签: authentication powershell certificate webclient


【解决方案1】:

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

【讨论】:

  • 这太完美了!非常感谢!
猜你喜欢
  • 2011-01-05
  • 2014-06-30
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
相关资源
最近更新 更多