medium.com 4 min read Original Source

Securing web applications with mTLS (ASP.NET Core 2.x)

If you’re actively doing web development, you’re probably familiar with Transport Layer Security (TLS) — or as its more commonly known, HTTPS.

TLS is a way of securing network traffic between a client and a server through the use of asymmetric cryptography. This protects the data from man-in-the-middle (mitm) attacks, as anybody sniffing the traffic across the network would just see a garbled mess.

Mutual TLS authentication (mTLS) takes this one step further by requiring both client and server to exchange and verify certificates.

The standard TLS encrypted tunnel is established for secure communications. Additionally, the client must also present its own certificate for the server to authenticate.

Here’s how to set up mTLS in an ASP.NET Core application.

The full code example is available in GitHub here.

Create a client certificate

This can be done using a number of different tools. I’ve chosen to use OpenSSL as this is an industry standard.

In Windows 10, I recommend installing Windows Subsystem for Linux (WSL). If you’re not sure how to do this, I’ve documented the process here.

In WSL, run the following commands:

client.pub
# Export the certificate in pkcs12 format
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
# Copy all files to a temporary folder in Windows
cp ./* /mnt/e/Temp/client” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

# Generate private key
openssl genrsa -out client.key 4096
# Generate certificate signing request (csr)
openssl req -sha256 -new -key client.key -out client.csr
# Generate a certificate from the csr
openssl x509 -req -sha256 -days 365 -in client.csr -signkey client.key -out client.cer
# Extract the public key
openssl rsa -in client.key -pubout > client.pub
# Export the certificate in pkcs12 format
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
# Copy all files to a temporary folder in Windows
cp ./* /mnt/e/Temp/client
# Generate private key
openssl genrsa -out client.key 4096
# Generate certificate signing request (csr)
openssl req -sha256 -new -key client.key -out client.csr
# Generate a certificate from the csr
openssl x509 -req -sha256 -days 365 -in client.csr -signkey client.key -out client.cer
# Extract the public key
openssl rsa -in client.key -pubout > client.pub
# Export the certificate in pkcs12 format
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
# Copy all files to a temporary folder in Windows
cp ./* /mnt/e/Temp/client

Here’s what it looks like running it on my system:

client.pub
writing RSA key
jordan@JORDAN-HOME:~/client$ openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
Enter Export Password:
Verifying – Enter Export Password:” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

jordan@JORDAN-HOME:~/client$ openssl genrsa -out client.key 4096
Generating RSA private key, 4096 bit long modulus
...................................................................................................................................................++
.......++
e is 65537 (0x010001)
jordan@JORDAN-HOME:~/client$ openssl req -sha256 -new -key client.key -out client.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:VIC
Locality Name (eg, city) []:Melbourne
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Contoso
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:jordan
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
jordan@JORDAN-HOME:~/client$ openssl x509 -req -sha256 -days 365 -in client.csr -signkey client.key -out client.cer
Signature ok
subject=C = AU, ST = VIC, L = Melbourne, O = Contoso, CN = jordan
Getting Private key
jordan@JORDAN-HOME:~/client$ openssl rsa -in client.key -pubout > client.pub
writing RSA key
jordan@JORDAN-HOME:~/client$ openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
Enter Export Password:
Verifying - Enter Export Password:
jordan@JORDAN-HOME:~/client$ openssl genrsa -out client.key 4096
Generating RSA private key, 4096 bit long modulus
...................................................................................................................................................++
.......++
e is 65537 (0x010001)
jordan@JORDAN-HOME:~/client$ openssl req -sha256 -new -key client.key -out client.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:VIC
Locality Name (eg, city) []:Melbourne
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Contoso
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:jordan
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
jordan@JORDAN-HOME:~/client$ openssl x509 -req -sha256 -days 365 -in client.csr -signkey client.key -out client.cer
Signature ok
subject=C = AU, ST = VIC, L = Melbourne, O = Contoso, CN = jordan
Getting Private key
jordan@JORDAN-HOME:~/client$ openssl rsa -in client.key -pubout > client.pub
writing RSA key
jordan@JORDAN-HOME:~/client$ openssl pkcs12 -export -out client.pfx -inkey client.key -in client.cer
Enter Export Password:
Verifying - Enter Export Password:

Import the certificate into Windows certificate storage

This step is only required if you want to debug locally.

Open the Microsoft Management Console (mmc) and do the following for both User and Computer certificates

  1. Import client.pfx into the Personal store
  2. Import client.cer into the Trusted Root store

MTLS authentication code

Here’s what my solution looks like:

Add Configuration

CertificateConfiguration.cs

namespace MtlsExample.Configurations
{
    public class CertificateConfiguration
    {
        public string Issuer { get; set; }
        public string PublicKey { get; set; }
    }
}
namespace MtlsExample.Configurations
{
    public class CertificateConfiguration
    {
        public string Issuer { get; set; }
        public string PublicKey { get; set; }
    }
}

appsettings.json

{
  "CertificateConfiguration": {
    "Issuer": "jordan",
    "PublicKey": "MIICIjANBgkqhk...60CAwEAAQ=="
  }
}
{
  "CertificateConfiguration": {
    "Issuer": "jordan",
    "PublicKey": "MIICIjANBgkqhk...60CAwEAAQ=="
  }
}

For PublicKey, use the value in client.pub created in the previous step.

Add client certificate middleware

ClientCertificateMiddleware.cs

<button data-code="using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace MtlsExample.Middleware
{
public class ClientCertificateMiddleware
{
private readonly RequestDelegate _next;
private readonly CertificateConfiguration _config;
public ClientCertificateMiddleware(RequestDelegate next, IOptions options)
{
_next = next;
_config = options.Value;
}
public async Task Invoke(HttpContext context)
{
try
{
var certHeader = context.Request.Headers["MS-ASPNETCORE-CLIENTCERT"];
var certBytes = Convert.FromBase64String(certHeader);
var cert = new X509Certificate2(certBytes);
var publicKey = Convert.ToBase64String(cert.GetPublicKey());
var issuer = cert.GetNameInfo(X509NameType.DnsName, true);
var subject = cert.GetNameInfo(X509NameType.DnsName, false);
if (publicKey == _config.PublicKey)
{
await _next.Invoke(context);
}
}
catch
{
context.Response.StatusCode = 403;
}
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace MtlsExample.Middleware
{
    public class ClientCertificateMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly CertificateConfiguration _config;
public ClientCertificateMiddleware(RequestDelegate next, IOptions<CertificateConfiguration> options)
        {
            _next = next;
            _config = options.Value;
        }
public async Task Invoke(HttpContext context)
        {
            try
            {
                var certHeader = context.Request.Headers["MS-ASPNETCORE-CLIENTCERT"];
                var certBytes = Convert.FromBase64String(certHeader);
                var cert = new X509Certificate2(certBytes);
                var publicKey = Convert.ToBase64String(cert.GetPublicKey());
                var issuer = cert.GetNameInfo(X509NameType.DnsName, true);
                var subject = cert.GetNameInfo(X509NameType.DnsName, false);
if (publicKey == _config.PublicKey)
                {
                    await _next.Invoke(context);
                }
            }
            catch
            {
                context.Response.StatusCode = 403;
            }
        }
    }
}
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace MtlsExample.Middleware
{
    public class ClientCertificateMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly CertificateConfiguration _config;
public ClientCertificateMiddleware(RequestDelegate next, IOptions<CertificateConfiguration> options)
        {
            _next = next;
            _config = options.Value;
        }
public async Task Invoke(HttpContext context)
        {
            try
            {
                var certHeader = context.Request.Headers["MS-ASPNETCORE-CLIENTCERT"];
                var certBytes = Convert.FromBase64String(certHeader);
                var cert = new X509Certificate2(certBytes);
                var publicKey = Convert.ToBase64String(cert.GetPublicKey());
                var issuer = cert.GetNameInfo(X509NameType.DnsName, true);
                var subject = cert.GetNameInfo(X509NameType.DnsName, false);
if (publicKey == _config.PublicKey)
                {
                    await _next.Invoke(context);
                }
            }
            catch
            {
                context.Response.StatusCode = 403;
            }
        }
    }
}

Note: The typical pattern for ASP.NET Core deployments is to place the application behind a reverse proxy. The certificate header will vary depending on what is used for the reverse proxy.

In Debug mode, this would be IIS Express (which uses the MS-ASPNETCORE-CLIENTCERT header.

If deploying in Azure app services the header would be X-ARR-ClientCert.

Add extension method for middleware

ClientCertMiddlewareExtensions.cs

<button data-code="using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
namespace MtlsExample.Middleware
{
public static class ClientCertMiddlewareExtensions
{
public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder, IOptions options)
{
return builder.UseMiddleware(options);
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
namespace MtlsExample.Middleware
{
    public static class ClientCertMiddlewareExtensions
    {
        public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ClientCertificateMiddleware>();
        }
public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder, IOptions<CertificateConfiguration> options)
        {
return builder.UseMiddleware<ClientCertificateMiddleware>(options);
        }
    }
}
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using MtlsExample.Configurations;
namespace MtlsExample.Middleware
{
    public static class ClientCertMiddlewareExtensions
    {
        public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ClientCertificateMiddleware>();
        }
public static IApplicationBuilder UseClientCertMiddleware(this IApplicationBuilder builder, IOptions<CertificateConfiguration> options)
        {
return builder.UseMiddleware<ClientCertificateMiddleware>(options);
        }
    }
}

Add certificate middleware to the Pipeline

Startup.cs

<button data-code="using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MtlsExample.Configurations;
using MtlsExample.Middleware;
namespace MtlsExample
{
public class Startup
{
private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure(_configuration.GetSection("CertificateConfiguration"));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseClientCertMiddleware();
app.UseMvc();
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MtlsExample.Configurations;
using MtlsExample.Middleware;
namespace MtlsExample
{
    public class Startup
    {
        private IConfiguration _configuration;
public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure<CertificateConfiguration>(_configuration.GetSection("CertificateConfiguration"));
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
app.UseClientCertMiddleware();
            app.UseMvc();
        }
    }
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MtlsExample.Configurations;
using MtlsExample.Middleware;
namespace MtlsExample
{
    public class Startup
    {
        private IConfiguration _configuration;
public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure<CertificateConfiguration>(_configuration.GetSection("CertificateConfiguration"));
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
app.UseClientCertMiddleware();
            app.UseMvc();
        }
    }
}

Create a test controller

MessageController.cs

using Microsoft.AspNetCore.Mvc;
namespace MtlsExample.Controllers
{
    [Route("")]
    public class MessageController : Controller
    {
        [HttpGet]
        public IActionResult GetMessage()
        {
            return Ok("Super Secret Message");
        }
    }
}
using Microsoft.AspNetCore.Mvc;
namespace MtlsExample.Controllers
{
    [Route("")]
    public class MessageController : Controller
    {
        [HttpGet]
        public IActionResult GetMessage()
        {
            return Ok("Super Secret Message");
        }
    }
}

Make IIS Express accept Client Certificates

IIS Express will not negotiate MTLS by default. We need to modify the applicationhost.config file to enable client certificates.

This file is located in *[solution folder].vs[solution name]config*

The applicationhost.config file is in XML format. Look for the and elements and set the values to the following:

<button data-code="
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<access sslFlags="Ssl, SslNegotiateCert, SslRequireCert" />
<iisClientCertificateMappingAuthentication enabled="true"></iisClientCertificateMappingAuthentication>
<access sslFlags="Ssl, SslNegotiateCert, SslRequireCert" />
<iisClientCertificateMappingAuthentication enabled="true"></iisClientCertificateMappingAuthentication>

You’ll need to restart Visual Studio after doing this for the settings to take effect.

Test it!

Start debugging and test it out in Postman:

References