AzureWeb应用作为客户端携带证书访问其他链接办法

这篇文章是之前早就写好的,今天整理时发现的,主要解决AzureWeb应用作为客户端携带证书访问其他链接可能出现的问题。

现象:有些时候应用服务可能需要作为客户端去访问其他自定义签名的https链接,或者在访问一些接口时需要携带证书去访问,关于公共证书cer文件您可以上传到Azure上面然后通过更改应用程序设置加入环境变量WEBSITE_LOAD_CERTIFICATES(值为*)在代码中读取,但是如果是p12这种在门户上面不支持添加的证书格式就需要您自己上传到磁盘下,再用代码读取了,这篇文档就是解决这个问题(也适用于cer证书)

解决方法

您可以使用下图中的方法去读取证书,然后将携带证书的请求发送出去:

public async Task<HttpResponseMessage> PostAsync()

{

       try {

              string url = "您的应用程序要访问的链接";

 

              var handler = new WebRequestHandler();

              handler.ClientCertificateOptions = ClientCertificateOption.Manual;

                           X509Certificate2 certificates = new X509Certificate2(@"您的证书路径", "证书密码", X509KeyStorageFlags.MachineKeySet);

                          

              handler.ClientCertificates.Add(certificates);

              handler.ClientCertificates.Add(certificates);

              handler.ServerCertificateValidationCallback = delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,

                                                                System.Security.Cryptography.X509Certificates.X509Chain chain,

                                                                System.Net.Security.SslPolicyErrors sslPolicyErrors) {return true; // **** Always accept

};

 

              using (var hc = new HttpClient(handler)) {

                     var httpContent = new StringContent("证书密码", Encoding.UTF8, "application/xml");

                     var response = await hc.PostAsync(url, httpContent);

                     return response;

              }

       }

       catch (Exception e) {

       Console.WriteLine(e);

       return null;

       }

}

需要注意的是X509Certificate2 certificates = new X509Certificate2(@"您的证书路径", "证书密码", X509KeyStorageFlags.MachineKeySet);此行代码中的X509KeyStorageFlags这个参数必须设置为X509KeyStorageFlags.MachineKeySet。

 

posted @ 2020-08-26 11:11  学习虾  阅读(222)  评论(0编辑  收藏  举报