在 Mono 上使用自定义 SSL 客户端证书 System.Net.HttpClient

Using custom SSL client certificates System.Net.HttpClient on Mono(在 Mono 上使用自定义 SSL 客户端证书 System.Net.HttpClient)
本文介绍了在 Mono 上使用自定义 SSL 客户端证书 System.Net.HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自 NuGet 的 Microsoft HTTP 客户端库,我基本上是在尝试允许 TLS使用 X509Certificate2 证书在 HttpClient 中进行身份验证.

I'm using Microsoft HTTP Client Libraries from NuGet and I'm basically trying to allow TLS authentication in HttpClient using X509Certificate2 certificates.

我尝试过这样创建客户端:

I have tried creating the client like this:

WebRequestHandler certHandler = new WebRequestHandler () {
    ClientCertificateOptions = ClientCertificateOption.Manual,
    UseDefaultCredentials = false
};
certHandler.ClientCertificates.Add (this.ClientCertificate);
HttpClient client = new HttpClient (certHandler);

但是 certHandler.ClientCertificates 失败了,因为这个 getter 是 没有在 Mono 中实现,所以我得到了 NotImplementedException.(我不确定为什么这仍然是 TODO.)

However certHandler.ClientCertificates is failing because this getter is not implemented in Mono, so I get a NotImplementedException from that. (I'm not sure why that's still a TODO.)

到目前为止,我运气不佳.任何想法如何在 Mono 环境中简单地在 HttpClient 上设置客户端证书?

So far I'm out of luck. Any ideas how can I simply set a client certificate on HttpClient in Mono environment?

推荐答案

貌似只是简单的可以把客户端证书集合传给CreateWebRequest中的HttpWebRequest,所以既然继承不行,我就干脆从单声道复制/粘贴类并添加实现.

It looks as if it's simply a matter of being able to pass the client certificate collection to the HttpWebRequest in CreateWebRequest, so since inheriting won't work, I just copy/pasted the class from mono and added the implementation.

// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Net.Cache;
using System.Net.Security;
using System.Security.Principal;
using System.Security.Cryptography.X509Certificates;

namespace System.Net.Http
{
    public class WebRequestHandlerWithClientcertificates : HttpClientHandler
    {
        bool allowPipelining;
        RequestCachePolicy cachePolicy;
        AuthenticationLevel authenticationLevel;
        TimeSpan continueTimeout;
        TokenImpersonationLevel impersonationLevel;
        int maxResponseHeadersLength;
        int readWriteTimeout;
        RemoteCertificateValidationCallback serverCertificateValidationCallback;
        bool unsafeAuthenticatedConnectionSharing;
        private X509CertificateCollection clientCertificates;

        public WebRequestHandler ()
        {
            allowPipelining = true;
            authenticationLevel = AuthenticationLevel.MutualAuthRequested;
            cachePolicy = System.Net.WebRequest.DefaultCachePolicy;
            continueTimeout = TimeSpan.FromMilliseconds (350);
            impersonationLevel = TokenImpersonationLevel.Delegation;
            maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
            readWriteTimeout = 300000;
            serverCertificateValidationCallback = null;
            unsafeAuthenticatedConnectionSharing = false;
        }

        public bool AllowPipelining {
            get { return allowPipelining; }
            set {
                EnsureModifiability ();
                allowPipelining = value;
            }
        }

        public RequestCachePolicy CachePolicy {
            get { return cachePolicy; }
            set {
                EnsureModifiability ();
                cachePolicy = value;
            }
        }

        public AuthenticationLevel AuthenticationLevel {
            get { return authenticationLevel; }
            set {
                EnsureModifiability ();
                authenticationLevel = value;
            }
        }

        public X509CertificateCollection ClientCertificates {
            get {
                if (clientCertificates==null) {
                    clientCertificates = new X509CertificateCollection();
                }
                return clientCertificates;
            }
            set {
                if (value==null) {
                    throw new ArgumentNullException("value");
                }
                EnsureModifiability ();
                clientCertificates = value;
            }
        }

        [MonoTODO]
        public TimeSpan ContinueTimeout {
            get { return continueTimeout; }
            set {
                EnsureModifiability ();
                continueTimeout = value;
            }
        }

        public TokenImpersonationLevel ImpersonationLevel {
            get { return impersonationLevel; }
            set {
                EnsureModifiability ();
                impersonationLevel = value;
            }
        }

        public int MaxResponseHeadersLength {
            get { return maxResponseHeadersLength; }
            set {
                EnsureModifiability ();
                maxResponseHeadersLength = value;
            }
        }

        public int ReadWriteTimeout {
            get { return readWriteTimeout; }
            set {
                EnsureModifiability ();
                readWriteTimeout = value;
            }
        }

        [MonoTODO]
        public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
            get { return serverCertificateValidationCallback; }
            set {
                EnsureModifiability ();
                serverCertificateValidationCallback = value;
            }
        }

        public bool UnsafeAuthenticatedConnectionSharing {
            get { return unsafeAuthenticatedConnectionSharing; }
            set {
                EnsureModifiability ();
                unsafeAuthenticatedConnectionSharing = value;
            }
        }

        internal override HttpWebRequest CreateWebRequest (HttpRequestMessage request)
        {
            HttpWebRequest wr = base.CreateWebRequest (request);

            wr.Pipelined = allowPipelining;
            wr.AuthenticationLevel = authenticationLevel;
            wr.CachePolicy = cachePolicy;
            wr.ImpersonationLevel = impersonationLevel;
            wr.MaximumResponseHeadersLength = maxResponseHeadersLength;
            wr.ReadWriteTimeout = readWriteTimeout;
            wr.UnsafeAuthenticatedConnectionSharing = unsafeAuthenticatedConnectionSharing;
            // here : maybe wr.ClientCertificates = ClientCertificates if the line below throws an error in your tests
            wr.ClientCertificates.Add(ClientCertificates);

            return wr;
        }
    }
}

现在在您的代码中使用 WebRequestHandlerWithClientCertificates 而不是 WebRequestHandler

now in your code use a WebRequestHandlerWithClientCertificates instead of a WebRequestHandler

这篇关于在 Mono 上使用自定义 SSL 客户端证书 System.Net.HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)