问题描述
尊敬的Stackoverflow用户
我已将一个天蓝色的密钥库自签名证书链接到我的Azure Web应用程序,启用了 minimum TLS v1.0,并将客户端证书模式设置为required
以强制SSL / TLS
如果我在Windows机器上安装了密钥库pfx证书并导航到我的URL(即:https://mywebapp.azurewebsites.net),浏览器会提示我使用我的证书,否则出现403 Frobidden错误,就可以了
当我在Xamarin android应用程序中加载此pfx时,我总是得到一个403 Frobidden error
。
这是我的代码:
using (httpclienthandler handler = new httpclienthandler() {
SslProtocols = System.Security.Authentication.SslProtocols.Tls12,AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,ClientCertificateOptions = ClientCertificateOption.Manual
})
{
//Add SSL certificat
X509Certificate2 _privateCert = GetPrivateAPICertificate(); //get a self-signed pfx stored localy in the android filesystem
if (_privateCert != null)
{
handler.ClientCertificates.Add(_privateCert);
handler.CheckCertificateRevocationList = false;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage,cert,cetChain,policyErrors) =>
{
return true; // <- when debugging return 2 Microsoft Azure certificate with subject *.azurewebsites.net but not the one I've added to my WebApp "TLS/SSL settings" blade.
};
}
using (HttpClient httpClient = new HttpClient(handler))
{
using (var request = new HttpRequestMessage { RequestUri = new Uri(url),Method = method })
{
response = await httpClient.SendAsync(request).ConfigureAwait(false);
responseAsstring = await response.Content.ReadAsstringAsync();
response.EnsureSuccessstatusCode(); // <- Throw exception: "Response status code does not indicate success: 403 (Forbidden)."
}
}
}
我在做什么错了?
编辑:添加了GetPrivateAPICertificate
功能
private X509Certificate2 GetPrivateAPICertificate()
{
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyCoreAssembly)).Assembly;
X509Certificate2 cert = new X509Certificate2();
using (StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("MyCoreAssembly.mycert.pfx")))
{
using (MemoryStream ms = new MemoryStream())
{
sr.BaseStream.copyTo(ms);
cert = new X509Certificate2(ms.ToArray());
}
}
return cert;
}
更新
我已经对邮递员进行了一些测试,如果我在邮递员的设置中添加了pfx证书,则可以访问Azure API。这不是Azure中的证书配置问题。
我不明白为什么我的HttpRequest
中没有从Xamarin发送证书!
更新2
我还将相同的完全相同的代码放入ASP.NET控制台应用程序中,并且可以正常工作。我想我必须在Xamarin的HTTP调用中添加一些内容...
解决方法
我终于找到了实现这一目标的方法。 以下帖子有重点: Xamarin Android - Call API using HttpClient with Certificate
通过使用HttpWebRequest
而不是HttpClient
,我可以发送带有证书的请求。
这是回归,因为HttpWebRequest
比新的HttpClient
实现要直观,但这是我到目前为止发现的唯一解决方案...