Programing

WebClient (C #)에 인증서를 어떻게 추가 할 수 있습니까?

lottogame 2020. 11. 2. 07:36
반응형

WebClient (C #)에 인증서를 어떻게 추가 할 수 있습니까?


HttpWebRequest에 인증서를 추가하는 것이 매우 간단하다는 것을 알고 있습니다. 그러나 WebClient를 사용하여 동등한 작업을 수행하는 방법을 찾지 못했습니다. 기본적으로 WebClient를 사용하여 특정 인증서로 POST를 보내고 싶습니다.

WebClient를 사용하여이 정확한 코드를 어떻게 수행 할 수 있습니까?

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

하나 이상의 함수를 하위 클래스로 분류하고 재정의해야합니다.

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.ClientCertificates.Add(new X509Certificate());
        return request;
    }
}

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:\n{0}",
            System.Text.Encoding.ASCII.GetString(responseArray));

그냥 subclass 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

An interesting thing happened when a new certificate was installed on our front-ends. We started getting the error:

"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.; The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.;"

We took care of the error by going to each front-end and opening the browser. It seems that IE was caching the old certificate. By opening the browsers, the new certificate took effect. Problem Solved!

참고URL : https://stackoverflow.com/questions/2066489/how-can-you-add-a-certificate-to-webclient-c

반응형