Search code examples
c#asp.netasp.net-corecertificate

.Net Core Web API with Client Certificate Authentication


I've developed a simple WEB API service in .Net Core 2.1

I'm trying to implement a client certificate authentication, so I can give access to the APIs only to the clients that have a specific certificate installed on their machine.

The clients access the API using a browser (Chrome, Edge, IE11 or Firefox).

I've added in the API method the request for the certificate:

[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{

    X509Certificate2 cert = Request.HttpContext.Connection.ClientCertificate;
    if (cert!=null && cert.Verify())
    {
        //more verification here...
        return Content("....", "application/json");
    }
    else
    {
        return Content("....", "application/json");
    }

}

then I've installed a self-signed certificate and added to the Trusted Root, enabling the Client Authentication purpose.

enter image description here

but the variable cert is always null and the browser didn't even prompt me to use a certificate when I request the page.

I suppose because I have to set somewhere that the web server must ask for the client certificate as it is possible to set in IIS, but in my development environment, I'm using IIS Express.

How can I force IIS express to request a client certificate?


Solution

  • For proper certificate authentication using the ASP.NET Core authentication stack, you can also check out idunno.Authentication.Certificate by Barry Dorrans himself. It allows you to enable certificate authentication for your application and handles it like any other authentication scheme, so you can keep actual certificate-based logic out of your business logic.

    This project sort of contains an implementation of Certificate Authentication for ASP.NET Core. Certificate authentication happens at the TLS level, long before it ever gets to ASP.NET Core, so, more accurately this is an authentication handler that validates the certificate and then gives you an event where you can resolve that certificate to a ClaimsPrincipal.

    You must configure your host for certificate authentication, be it IIS, Kestrel, Azure Web Applications or whatever else you're using.

    Make sure to also check out the “documentation” on how to set this up properly, since it requires configuration of the host to work properly, just like you did with IIS Express. Instructions for other servers like raw Kestrel, IIS, Azure or general reverse proxies are included.