使用https协议进行通信的时候能够设置双向证书认证,客户端验证服务端证书的方法前面已经介绍过了,如今说一下在服务端验证客户端证书的方案。对象
这里给出的方案比较简单,只须要在Service端的配置文件中配置好Client端的证书的Thumbprint(一个或者多个),姑且称之为证书白名单。当有Client端的Http请求的时候,blog
只须要使用HttpRequestMessage的扩展方法GetClientCertificate()方法获取该请求所携带的证书,并验证该证书的Thumbprint是否包含在配置文件的白名单中,若是不包含在白名单中,it
在拦截该请求,并报401(未受权)错误便可;不然,继续执行该请求。io
注意:class
GetClientCertificate()方法是HttpRequestmessage对象的扩展方法,该方法定义在System.Net.Http命名空间下的HttpRequestMessageExtensions类中。该方法返回的是一个X509Certificate对象。cli
客户端携带证书发出请求:扩展
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); } }