How to implement Certificate Authentication in ASP.NET Core

How to implement Certificate Authentication in ASP.NET Core

Certificate-based Authentication is the use of a Digital Certificate to identify a client request before granting it the access to a resource, network, application, etc. Certificate Authentication provides added security to web applications. You can easily implement it in ASP.NET Core 3.0. Let us understand how to do it.

Certificate Authentication is a great way to secure your ASP.NET Core APIs. I have provided the full source that can be downloaded at the end of this tutorial.

Implementing Certificate Based Authentication

In your ASP.NET Core app, first add the package called Microsoft.AspNetCore.Authentication.Certificate from NuGet.

Next, in the Startup.cs file’s ConfigureServices() method, call the AddAuthentication() method, and provide a delegate for OnCertificateValidated and OnAuthenticationFailed events.

Check the below code which does the exact thing:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    
    services.AddAuthentication(
        CertificateAuthenticationDefaults.AuthenticationScheme)
        .AddCertificate(options =>
        {
            options.Events = new CertificateAuthenticationEvents
            {
                OnCertificateValidated = context =>
                {
                    var validationService = context.HttpContext.RequestServices.GetService<MyCertificateValidationService>();

                    if (validationService.ValidateCertificate(context.ClientCertificate))
                    {
                        context.Success();
                    }
                    else
                    {
                        context.Fail("invalid cert");
                    }

                    return Task.CompletedTask;
                },
                OnAuthenticationFailed = context =>
                {
                    context.Fail("invalid cert");
                    return Task.CompletedTask;
                }
            };
        });
}

Note that inside the OnAuthenticationFailed event you show ‘invalid cert’ message.

I have also specified MyCertificateValidationService class where the certificate will be validated. It’s full code is given below:

public class MyCertificateValidationService
{
    public bool ValidateCertificate(X509Certificate2 clientCertificate)
    {
        var cert = new X509Certificate2(Path.Combine("localhost_root_l1.pfx"), "1234");
        if (clientCertificate.Thumbprint == cert.Thumbprint)
        {
            return true;
        }

        return false;
    }
}
I covered ASP.NET Core Action method in full details in my tutorial. I am sure you will discover new ways to work with them in your apps.
Next, add app.UseCertificateForwarding() & app.UseAuthentication(); methods inside the Configure() method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseCertificateForwarding();
    app.UseAuthentication();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Configure your app to require certificates

Finally, you have to configure Kestrel so that the application always require certificates. This is done by adding the below code to the Program.cs file:
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureKestrel(options =>
        {
            options.ConfigureHttpsDefaults(opt => 
                opt.ClientCertificateMode = 
                    ClientCertificateMode.RequireCertificate);
        })
        .Build();

Download full source codes:

Download
Conclusion
Congrats you have successfully implemented the Certificate Authentication system in your app. You app now becomes more secure than before.
Next tutorials of great interest:

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

5 responses to “How to implement Certificate Authentication in ASP.NET Core”

  1. Yong Seo says:

    Thanks much for your wonderful tutorial for the client certificate. I am having a problem connecting to the service from my console client.

    var cert = new X509Certificate2(@”c:\…\root_localhost.pfx”, “1234”);
    var handler = new HttpClientHandler();
    handler.ClientCertificates.Add(cert);
    var client = new HttpClient(handler);
    var request = new HttpRequestMessage()
    {
    RequestUri = new Uri(“https://localhost”),
    Method = HttpMethod.Get,
    };
    var response = await client.SendAsync(request);
    if (!response.IsSuccessStatusCode)
    {
    //I am getting 403 always
    }

    I checked “Require SSL” on IIS SSL Ssettings and checked “Client Certirficate” to be “Required”.

    I can’t figure out how to make it work.
    Any help and advice are appreciated.

    Thank again.
    Yong

  2. yogihosting says:

    Most probably the reason can be the Certificate is not allowed by the browser. You should try regenerating a new Root and client certificates from the Powershell command. Hope it helps you.

    Regards,
    Yogi

  3. nizar elouaer says:

    Thanks for the post. I implanted my certificate authentication based on your post. When I run my application in my windows 10 machine everything works correctly. However when I use docker, call my url (for example https://localhost:5001/api) I am having e err_connection_closed issue. Any suggestion please ? Thank you

  4. nizar elouaer says:

    Hello. thank you for the post. I used the tutorial to add certifccate authentication in my app, it owrks perfectly on Windows. However when I execute the app on Ubuntu, I am always having an “ERR_CONNECTION_CLOSED”. I generated a certificate using openssl on my ubuntu machine but I am still having the same issue.
    PS: if I comment the lines
    “””
    .ConfigureKestrel(options =>
    {
    options.ConfigureHttpsDefaults(opt =>
    opt.ClientCertificateMode =
    ClientCertificateMode.RequireCertificate);
    })
    “””
    I am able to get a response, however the request has no certificate.

    Any idea ? Thank you

  5. Jonathan Conley says:

    I run sample code and get Access to localhost was denied You don’t have authorization to view this page.
    HTTP ERROR 403

Leave a Reply

Your email address will not be published. Required fields are marked *