使用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);
                    }
          }

  

相关文章:

  • 2021-11-02
  • 2021-11-23
  • 2021-06-12
  • 2021-06-04
  • 2021-10-22
  • 2021-12-10
  • 2021-06-23
猜你喜欢
  • 2022-12-23
  • 2021-04-09
  • 2022-02-05
  • 2021-09-01
  • 2021-11-29
  • 2021-11-23
相关资源
相似解决方案