SSL Certificate authentication in ASP.NET Core

Have you ever wondered, even though you added a certificate to HttpClient while accessing data from the Api service, why you are getting unAuthorized access or your Api is not working as expected?
Answer to the above question is that the certificate exchange is done at the start of the HTTPS conversation, it's done by the server before the first request is received on that connection. So the right place to add a certificate to HttpClient is the Program.cs or StartUp.cs file.

Microsoft.AspNetCore.Authentication.Certificate contains an implementation similar to Certificate Authentication for ASP.NET Core. Certificate authentication happens at the TLS level, long before it ever gets to ASP.NET Core. 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.

Implement an HttpClient using a certificate and IHttpClientFactory

In the following example, a client certificate is added to a HttpClientHandler using the ClientCertificates property from the handler. This handler can then be used in a named instance of an HttpClient using the ConfigurePrimaryHttpMessageHandler method. This is setup in Program.cs:

var clientCertificate =

    new X509Certificate2(

      Path.Combine(_environment.ContentRootPath, "mysample_cert.pfx"), "12345678");

 

builder.Services.AddHttpClient("namedClient", c =>

{

}).ConfigurePrimaryHttpMessageHandler(() =>

{

    var handler = new HttpClientHandler();

    handler.ClientCertificates.Add(clientCertificate);

    return handler;

});

 

The IHttpClientFactory can then be used to get the named instance with the handler and the certificate. The CreateClient method with the name of the client defined in Program.cs is used to get the instance. The HTTP request can be sent using the client as required:

 

public class SampleHttpService

{

    private readonly IHttpClientFactory _httpClientFactory;

 

    public SampleHttpService(IHttpClientFactory httpClientFactory)

        => _httpClientFactory = httpClientFactory;

 

    public async Task<JsonDocument> GetAsync()

    {

        var httpClient = _httpClientFactory.CreateClient("namedClient");

        var httpResponseMessage = await httpClient.GetAsync("https://sample.com");

 

        if (httpResponseMessage.IsSuccessStatusCode)

        {

            return JsonDocument.Parse(

                await httpResponseMessage.Content.ReadAsStringAsync());

        }

 

        throw new ApplicationException($"Status code: {httpResponseMessage.StatusCode}");

    }

}

 

If the correct certificate is sent to the server, the data is returned. If no certificate or the wrong certificate is sent, an HTTP 403 status code is returned.

Comments

Popular posts from this blog

Belekeri, Karwar Beach Photos

Publish an Angular with .NET CORE app to IIS on AWS Cloud EC2 instance