GetRequestContext()。ClientCertificate始终返回null

时间:2018-03-27 05:51:23

标签: c# asp.net-web-api2

我正在使用自托管Web API进行基于客户端证书的身份验证,但在尝试使用请求获取证书时,Web API始终返回null     GetRequestContext()。ClientCertificate

以下是Web API端的代码

    protected override System.Threading.Tasks.Task<HttpResponseMessage>
                SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
  HttpResponseMessage response = ValidateCertificate(request);
            if (response.StatusCode == HttpStatusCode.OK)
                return base.SendAsync(request, cancellationToken);
            else
                return Task<HttpResponseMessage>.Factory.StartNew(() => response);
        }

private HttpResponseMessage ValidateCertificate(HttpRequestMessage request)
        {
            var certificateFromRequest = request.GetRequestContext().ClientCertificate;

            if (certificateFromRequest == null)
            {
                return request.CreateResponse(HttpStatusCode.NotAcceptable, "Certificate is not available in request!");
            }

在客户端代码是:

WebRequestHandler handler = new WebRequestHandler();
            X509Certificate2 certificate = ConfigurationManager.AppSettings["MSIClientCertificateThumbprint"].CleanThumbprint().GetCertByThumbprint();

            handler.ClientCertificates.Add(certificate);
using (var httpClient = new HttpClient(handler))
            {
                var response = await httpClient.PostAsync($"{ConfigurationManager.AppSettings["WEBAPIPATH"]}/api/controller/{param}", null);
                response.EnsureSuccessStatusCode();
            }

我总是看到证书正在HTTPClient中正确传递,其中包含私钥,但仍然无法找到它

1 个答案:

答案 0 :(得分:0)

通过从net452将客户端项目更新为net461来解决此问题。

在添加客户端证书时,HttpClient要求私钥在证书上可用

我从以下PowerShell命令生成证书

New-SelfSignedCertificate -Subject "Subject" -FriendlyName "Name" -NotAfter (Get-Date).AddYears(5) -CertStoreLocation cert:\localmachine\my 

生成基于CNG加密密钥的私钥,net452不支持

此外,在将客户端项目更新为net461后,我必须向PowerShell命令添加其他参数以生成证书

New-SelfSignedCertificate -Subject "UcClearly" -FriendlyName "UcClearly.MSI.API" -NotAfter (Get-Date).AddYears(5) -CertStoreLocation cert:\localmachine\my -KeyExportPolicy Exportable -KeySpec Signature