【问题标题】:Getting client certificate获取客户端证书
【发布时间】:2021-04-21 17:59:32
【问题描述】:

我需要在我的 .NET 5 Web API 中的一些端点上实现客户端证书身份验证。所以我不想像here in the MS docs 描述的那样在所有端点上启用 HTTPS。我在本地机器上使用 Kestrel,而不是 IIS express 或 IIS。

我尝试了以下三种方法,但都没有成功:

var clientCertHeaders = context.HttpContext.Request.Headers;

这个返回请求的正常标头,但没有证书。

var clientCert = context.HttpContext.Connection.ClientCertificate;
var clientCertAsync = context.HttpContext.Connection.GetClientCertificateAsync().Result;

这两个都返回null。

我已尝试将以下内容应用于我的服务:

services.AddCertificateForwarding(options =>
    {
        options.CertificateHeader = "X-SSL-CERT";
        options.HeaderConverter = (headerValue) =>
        {
            X509Certificate2 clientCertificate = null;

            if(!string.IsNullOrWhiteSpace(headerValue))
            {
                var bytes = Encoding.UTF8.GetBytes(headerValue);
                clientCertificate = new X509Certificate2(bytes);
            }

            return clientCertificate;
        };
    });

即使在我的服务中启用了该功能,我也不会检索客户端证书。

我正在使用 Postman 向 API 请求发出请求。

【问题讨论】:

  • 在您的 IIS 链接上有 SSL 设置的三个选项 1) 忽略 2) 接受 3) 要求。您可以使用选项 2。

标签: c# asp.net-core .net-5


【解决方案1】:

您需要配置 Kestrel 以允许在 program.cs 中使用客户端证书。默认值为 ClientCertificateMode.NoCertificate,因此在您的 ConfigureWebHostDefaults 中您需要将其更改为 ClientCertificateMode.AllowCertificate

这是您发送给我的文档中经过编辑的代码块:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.ConfigureKestrel(o =>
            {
                o.ConfigureHttpsDefaults(o => 
                o.ClientCertificateMode = 
                ClientCertificateMode.AllowCertificate);
            });
        });
}

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2014-11-01
    • 2019-05-02
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    相关资源
    最近更新 更多