使用HttpClient的多个证书

时间:2014-12-16 09:15:10

标签: c# azure ssl 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;

 }

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

1 个答案:

答案 0 :(得分:1)

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

对服务API使用带有承载令牌和Azure AD身份验证的OAuth授权,而不是证书。

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

您可以在authenticating service management API calls with Azure AD here上阅读更多内容。

您可以学习more about using ADAL with Windows Phone app here

您授予本机客户端应用程序访问Azure Service Management API的权限:

enter image description here