Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting client certificate

I need to implement Client Certificate authentication on some of the endpoints in my .NET 5 Web API. So I don't want to enable HTTPS across all endpoint as described here in the MS docs. I am using Kestrel on my local machine and not IIS express or IIS.

I have tried the following three methods with no luck on either of them:

var clientCertHeaders = context.HttpContext.Request.Headers;

This one returns the normal headers for the request but no certificate.

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

These two both return null.

I've tried applying the following to my services:

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;
        };
    });

Even with that enabled in my services I am not retrieving the client certificate.

I am using Postman to make the requests to the API requests.

like image 469
Tachyon Avatar asked Jan 29 '26 06:01

Tachyon


1 Answers

You need to configure Kestrel to allow client certificates in the program.cs The default value is ClientCertificateMode.NoCertificate so in your ConfigureWebHostDefaults you need to change that to ClientCertificateMode.AllowCertificate.

Here's an edited chunk of code from the docs you sent where I did that:

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);
            });
        });
}
like image 66
Michal Rosenbaum Avatar answered Jan 31 '26 19:01

Michal Rosenbaum