top of page
Writer's pictureThe Tech Platform

Certificate Based Authentication in ASP.Net core Web API



Certificate-based authentication is the use of a Digital Certificate to identify a user, machine, or device before granting access to a resource, network, application, etc.

Let’s see example

Create a certificate

using windows PowerShell, I am generating a simple self-signed certificate for test.

It will generate a certificate in current directory.

dotnet dev-certs https -ep dev_cert.pfx -p 1234

Create web API

Create a webapi app with following command.

dotnet new webapi -o CerificateAuth

add the required nuget package

dotnet add package Microsoft.AspNetCore.Authentication.Certificate

Program.cs

Open Program.cs and make the following changes.

Program.cs changes


It tells Kestrel that it needs a certificate to allow any further communication.

Certificate Validation

Add a class which does the certificate validation and add following method.

certificate validation


Note: In production, reading certificate should be done via any secure vault.

Authentication Extension

Add a extension class to configure authentication.

public static class AuthenticationExtension    
{
    public static void ConfigureAuthetication(this 
                            IServiceCollection services)        
    {    
        services.AddAuthentication
                        (CertificateAuthenticationDefaults.
                         AuthenticationScheme)                
        .AddCertificate(options=>                
        {
           options.RevocationMode = X509RevocationMode.NoCheck;
          options.AllowedCertificateTypes=CertificateTypes.All;
           options.Events = new CertificateAuthenticationEvents                    
            {
                OnCertificateValidated=context=>                        
                {
                    var validationService =     
                        context.HttpContext.RequestServices.
                    GetService<CertificateValidationService>();
                    
                    if (validationService != null &&                       
                        validationService.ValidateCertificate
                        (context.ClientCertificate))                            
                    {
                        Console.WriteLine("Success");
                        context.Success();                            
                    }
                    else                            
                    {
                        Console.WriteLine("invalid cert");
                        context.Fail("invalid cert");                            
                    }
                    return Task.CompletedTask;                        
                }                    
            };                
        });
        services.AddAuthorization();        
    }    
}

In this example, we are simply validating the certificate and returning success, we can extract claims after successful validation.

Startup.cs

Finally we add required code in startup.cs

Startup.cs changes


Controller

we also have to specify the authorize attribute to required controllers.

controller changes


we are done with changes in API

Let’s build and run to make sure no build errors.


Create client

Create a console app with following command.

dotnet new console -o CerificateAuthClient

and add the following code

It is simple client with httpclient, calling API with attaching the certificate.

when we run the client. we get following result.


We have got the response back.


Test With Postman

Make sure your API is running.

First add the certificate to postman. go to Settings -> Certificates and select add certificate. and add the required info like below.


Once the certificate is added, we can call our API.


we can see the result as we successfully get the response back.

You can find full source code at Github


Summary

This is just a simple example. of course we can achieve more with certificate based authentication.



Source: Medium - Nitesh Singhal


The Tech Platform

Recent Posts

See All

Kommentare


bottom of page