获取客户端证书

时间:2021-04-21 09:42:11

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

我需要在我的 .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 请求发出请求。

1 个答案:

答案 0 :(得分: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);
            });
        });
}