使用HttpClient的多个证书

Sri*_*har 17 c# ssl azure windows-phone-8.1

我正在构建一个Windows Phone 8.1应用程序,允许Azure用户使用Azure Service Management API查看其订阅/服务.使用管理证书完成身份验证,并将证书附加到API的所有请求.它适用于单个用户.但是当我尝试为多个订阅包含一个功能时,问题就出现了.我可以在证书库中安装证书并检索它.但是当我将请求发送到API时会出现问题.即使我附加了正确的证书,我也会收到403禁止错误.这是我用过的代码.

public async Task<Certificate> GetCertificate()
{
          await CertificateEnrollmentManager.ImportPfxDataAsync(Certificate, "", ExportOption.Exportable, KeyProtectionLevel.NoConsent, InstallOptions.None, SubscriptionID);
          CertificateQuery query = new CertificateQuery();
          query.FriendlyName = SubscriptionID;
          var c = await CertificateStores.FindAllAsync(query);
          return c[0];
}

public async Task<HttpResponseMessage> SendRequest(string url,string version)
{
        HttpResponseMessage response = null;
        try
        {
            HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
            filter.ClientCertificate = await GetCertificate();
            HttpClient client = new HttpClient(filter);
            HttpRequestMessage request = new HttpRequestMessage();
            request.RequestUri = new Uri(url);
            request.Headers.Add("x-ms-version", version);
            response = await client.SendRequestAsync(request, 0);
            return response;
        }
        catch(Exception e)
        {
            var status=Windows.Web.WebError.GetStatus(e.HResult);
            if (status == WebErrorStatus.CannotConnect)
                throw new Exception("Cannot connect to internet. Check your connection.");
            else if (status == WebErrorStatus.Disconnected)
                throw new Exception("Connection was disconnected.");
            else if (status == WebErrorStatus.ServiceUnavailable)
                throw new Exception("Server was unavailable");
            else if (status == WebErrorStatus.ConnectionReset)
                throw new Exception("Connection was reset.");
            else if (status == WebErrorStatus.BadGateway)
                throw new Exception("Bad gateway.");
            else if (status == WebErrorStatus.InternalServerError)
                throw new Exception("Internal server error occurred");
            else if (status == WebErrorStatus.HostNameNotResolved)
                throw new Exception("Check your network connection. Host name could not be resolved.");
        }
        return response;

 }
Run Code Online (Sandbox Code Playgroud)

Windows Phone操作系统是否对应用程序的证书有限制?

ast*_*kov 1

虽然没有真正直接回答如何处理您的证书问题,但我建议您采用一种效果更好的解决方法。

将 OAuth 授权与不记名令牌和 Azure AD 身份验证一起用于服务 API,而不是证书。

因此,您只需使用 ADAL 从 Azure AD 获取令牌,而不需要管理多个证书。您收到的单个令牌将对用户有权访问的所有订阅有效。

您可以在此处阅读有关使用 Azure AD 验证服务管理 API 调用的更多信息。

您可以在此处了解有关将 ADAL 与 Windows Phone 应用程序结合使用的更多信息

您授予本机客户端应用程序对 Azure 服务管理 API 的访问权限:

在此输入图像描述