【问题标题】:Client certificate is always null客户端证书始终为空
【发布时间】:2019-02-22 18:34:59
【问题描述】:

我在个人以及受信任的根证书颁发机构

下安装了一个证书

已尝试使用这段代码发布到端点:

public void Post()
    {
        try
        {
            var clientCert = LoadFromStore("MyThumbprint");
            var requestHandler = new WebRequestHandler();

            requestHandler.ClientCertificates.Add(clientCert);

            var client = new HttpClient(requestHandler)
            {
                BaseAddress = new Uri("https://localhost:44430/")
            };

            var response = client.GetAsync("api/test").Result;
            response.EnsureSuccessStatusCode();

            string responseContent = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(responseContent);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception while executing the test code: {0}", ex.Message);
        }
    }

经过检查,.ClientCertificate 属性始终为空。

 [Route("api/[controller]")]
public class TestController : Controller
{
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        var clientCertInRequest = Request.HttpContext.Connection.ClientCertificate;
        if (clientCertInRequest != null) return Ok();

        return BadRequest("No certificate found");
    }

}

想知道是否有人以前遇到过此问题或知道如何将证书发布到 webapi 端点并能够检索和验证?

非常感谢

【问题讨论】:

    标签: c# security asp.net-core-webapi x509certificate x509certificate2


    【解决方案1】:
    1. 确保您使用真正的 IIS 而不是 express
    2. 配置 IIS 使其接受证书
    3. 在配置或活动目录中配置映射证书
    4. 在浏览器中尝试请求,看看是否弹出证书选择对话框
      • 如果不是基于 HTTP 错误子状态码诊断
      • 如果是这样,请再次运行您的代码

    【讨论】:

      【解决方案2】:

      您必须知道,服务器端响应证书取决于证书类型/证书内容。 当我推送 自签名证书(在 IIS 中本地生成)时,我遇到了同样的问题:请求证书中的服务器上始终为空。 但是当我推送 普通(公共)证书,带有链式层次结构 - 我很惊讶,因为我收到了证书!!

      所以我建议第一次生成公共证书在免费的Certificate授权中心,比如https://www.sslforfree.com/

      【讨论】:

        【解决方案3】:

        .Net 6:

        builder.WebHost.ConfigureKestrel(kestrel =>
        {
            kestrel.ConfigureHttpsDefaults(https => https.ClientCertificateMode = ClientCertificateMode.AllowCertificate);
        });
        

        旧版本:

        return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.ConfigureKestrel(o =>
                    {
                        o.ConfigureHttpsDefaults(o => 
                        o.ClientCertificateMode = 
                        ClientCertificateMode.AllowCertificate);
                    });
                });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-28
          • 2015-08-07
          • 1970-01-01
          • 2015-10-01
          • 1970-01-01
          • 2019-04-06
          • 1970-01-01
          • 2015-09-06
          相关资源
          最近更新 更多