Xamarin Android - 使用 HttpClient with TCertificate 调用 API



我们正在尝试与我们的API进行通信,该API需要在请求中提供证书,但它不能很好地工作。

通常,我们仅通过在请求标头中传递订阅密钥来使用外部服务或Azure API 管理 API,但这次我们有一个证书 (.cer),我们需要在 AndroidHttpClientHandler 中注入,但此功能似乎不受支持,或者我们用错了?

你知道这种情况是否真的可能吗,如果是,我们应该如何实现它?我尝试了很多事情,例如创建自定义的AndroidHttpClientHandler以允许在其中放置ClientCertificate,但没有成功。

终于设法让它工作:D对于那些感兴趣的人,这是我实现它的方法:

TL;DR:升级到Visual Studio 2019,HttpWebRequest来救援(你可以在下面找到代码示例);-)

上下文:我们的项目由一个 PCL 和一个 Android 项目组成。在团队中,我们知道我们必须将PCL迁移到.NET Standard项目,但这需要时间,特别是当您有很多库要处理(未更新到.NET Standard的库)xP

  • 当您要调用 API 时,您想到的第一件事是使用 HttpClient/HttpRequestHandler 对,我们只需要在 HttpRequestHandler 中传递我们的证书,如下所示:

    httpRequestHandler.ClientCertificates.Add(new X509Certificate2(..))

为什么它不起作用?因为我们是使用Xamarin.Android开发的,它使用Mono.Droid,因此我们遇到了不受欢迎的NotImplementException()!WebRequestHandler 怎么样?好吧,同样的命运:P

希望救赎来自HttpWebRequest,如下所示:

private Task<string> ExecuteRequest(Uri uri, X509Certificate2 certificate)
{
// Create a web request that points to our secured Backend API
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
if (certificate != null)
{
// Associate the certificates with the request
request.ClientCertificates.Add(certificate);
}
// Launch the web request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Output the stream to a jsonTextReader or anything else depending on your needs
using (Stream stream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
// Do whatever you want
}
}

这段代码适用于我的机器(Visual Studio 2019),但不适用于我的同事(Visual Studio 2017):确实遇到了以下异常:

System.Security.Authentication.AuthenticationException:对 SSPI 的调用失败,请参阅内部异常

我的机器上还安装了VS2017,所以我尝试使用它执行相同的代码,听起来很奇怪,我也得到了错误

瞧:)当然,证书必须是"嵌入式资源">

最新更新