zoukankan      html  css  js  c++  java
  • C#在服务端验证客户端证书(Certificate)

    使用https协议进行通讯的时候可以设置双向证书认证,客户端验证服务端证书的方法前面已经介绍过了,现在说一下在服务端验证客户端证书的方案。

    这里给出的方案比较简单,只需要在Service端的配置文件中配置好Client端的证书的Thumbprint(一个或者多个),姑且称之为证书白名单。当有Client端的Http请求的时候,

    只需要使用HttpRequestMessage的扩展方法GetClientCertificate()方法获取该请求所携带的证书,并验证该证书的Thumbprint是否包含在配置文件的白名单中,如果不包含在白名单中,

    在拦截该请求,并报401(未授权)错误即可;否则,继续执行该请求。

    注意:

    GetClientCertificate()方法是HttpRequestmessage对象的扩展方法,该方法定义在System.Net.Http命名空间下的HttpRequestMessageExtensions类中。该方法返回的是一个X509Certificate对象。

    客户端携带证书发出请求:

               
              var clientCertificate = ...;//获取本地证书对象
              using (WebRequestHandler handler = new WebRequestHandler())
                    {
                        handler.ClientCertificates.Add(clientCertificate);
                        using (HttpClient httpClient = new HttpClient(handler))
                        {
                            var request = new HttpRequestMessage(method: httpMethod, requestUri: requestUri);
                      
                            if (requestContent != null)
                            {
                                request.Content = requestContent;
                            }
    
                            return await httpClient.SendAsync(request);
                        }
              }

      

  • 相关阅读:
    何谓B/S架构,C/S架构,SOA架构?
    Android牟利之道广告平台的介绍
    软件开发工具介绍
    jQuery Mobile 入门教程
    程序员的编辑器——VIM
    优秀程序员值得借鉴的一些信息
    程序员必备利器——敏捷软件
    PhoneGap Build的使用
    PhoneGap简单介绍
    ceph16.2.6 cephfs mds源码阅读
  • 原文地址:https://www.cnblogs.com/Herzog3/p/6374534.html
Copyright © 2011-2022 走看看