如何通过httpwebrequest访问使用证书登录的网站

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过httpwebrequest访问使用证书登录的网站相关的知识,希望对你有一定的参考价值。

参考技术A 如何通过httpwebrequest访问使用证书登录的网站
首先找根目录下有没有.sln文件,这是解决方案,如果有的话双击,VS会自己按照它的目录格式将所有项目导入..

如果没有.sln.找.proj文件,这个就是下面1个1个的项目文件了,也是双击打开,这里打开了只是1个单独的项目..

还是没有的话,直接在VS的文件-打开网站,选择你这个根目录就行了...不过这样子的源码要吗是编译了底层源码的,要吗就是源码没分层全在app_code里面的,这种学习和使用价值就不高了

如何向 WebClient (C#) 添加证书?

【中文标题】如何向 WebClient (C#) 添加证书?【英文标题】:How can you add a Certificate to WebClient (C#)? 【发布时间】:2011-01-05 04:58:22 【问题描述】:

我知道将证书添加到 HttpWebRequest 非常简单。但是,我还没有找到使用 WebClient 进行等效操作的方法。基本上,我想使用 WebClient 发送带有特定证书的 POST。

你将如何使用 WebClient 完成这个确切的代码:

var request = (HttpWebRequest) WebRequest.Create("my-url");
request.Method = "POST";
request.ClientCertificates.Add(new X509Certificate()); //add cert

【问题讨论】:

注意未来的答案寻求者,微软建议使用较新的 HttpClient 而不是 WebClient:We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class. 【参考方案1】:

只需继承WebClient,添加您自己的ClientCertificates 属性并覆盖WebClient.GetWebRequest(System.Uri) 方法。我没有时间将它从 VB 转换为 C#,但它应该是不言自明的:

Imports System.Net

Public Class WebClient2
    Inherits System.Net.WebClient

    Private _ClientCertificates As New System.Security.Cryptography.X509Certificates.X509CertificateCollection
    Public ReadOnly Property ClientCertificates() As System.Security.Cryptography.X509Certificates.X509CertificateCollection
        Get
            Return Me._ClientCertificates
        End Get
    End Property
    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim R = MyBase.GetWebRequest(address)
        If TypeOf R Is HttpWebRequest Then
            Dim WR = DirectCast(R, HttpWebRequest)
            If Me._ClientCertificates IsNot Nothing AndAlso Me._ClientCertificates.Count > 0 Then
                WR.ClientCertificates.AddRange(Me._ClientCertificates)
            End If
        End If
        Return R
    End Function
End Class

【讨论】:

【参考方案2】:

您必须继承并覆盖一个或多个函数。

class MyWebClient : WebClient

    protected override WebRequest GetWebRequest(Uri address)
    
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.ClientCertificates.Add(new X509Certificate());
        return request;
    

【讨论】:

太棒了!一直试图弄清楚如何做到这一点太久了【参考方案3】:

在我们的前端安装新证书时发生了一件有趣的事情。我们开始收到错误:

“底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。;底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。;”

我们通过转到每个前端并打开浏览器来处理错误。似乎 IE 正在缓存旧证书。通过打开浏览器,新证书生效。问题解决了!

【讨论】:

【参考方案4】:
public class CertificateWebClient : WebClient

    private readonly X509Certificate2 certificate;

    public CertificateWebClient(X509Certificate2 cert)
    
        certificate = cert;
    

    protected override WebRequest GetWebRequest(Uri address)
    
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);

        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj, X509Certificate X509certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors)
        
            return true;
        ;

        request.ClientCertificates.Add(certificate);
        return request;
    

现在您可以使用自签名证书了! ("底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。;底层连接已关闭:无法为 SSL/TLS 安全通道建立信任关系。;")

        X509Certificate2 Cert = new X509Certificate2("client.p12", "1234", X509KeyStorageFlags.MachineKeySet);

        // Create a new WebClient instance.
        CertificateWebClient myWebClient = new CertificateWebClient(Cert);

        string fileName = Installation.destXML;
        string uriString = "https://xxxxxxx.xx:918";
        // Upload the file to the URI.
        // The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
        byte[] responseArray = myWebClient.UploadFile(uriString, fileName);

        // Decode and display the response.
        Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n0",
            System.Text.Encoding.ASCII.GetString(responseArray));

【讨论】:

如果您将证书添加到 webRequest.ClientCertificates 那么您不再需要覆盖 ServerCertificateValidationCallback ,这是一个全局设置,因此您会影响一切 如果你有这个异常消息The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel添加这个ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

以上是关于如何通过httpwebrequest访问使用证书登录的网站的主要内容,如果未能解决你的问题,请参考以下文章

将自签名证书与 .NET 的 HttpWebRequest/Response 一起使用

Linux中用HttpWebRequest或WebClient访问远程https路径

vb.net如何访问https网页

使用 HttpClient 检查服务器证书

强制 HttpWebRequest 发送客户端证书

C# HttpWebRequest 绝技 根据URL地址获取网页信息