Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Certificates, TLS and mTLS

Issue and auto-renew certificates with ACM, decide when AWS Private CA is worth paying for, pick strict TLS policies on ALB and API Gateway, and build mutual TLS between a partner and a .NET API.

intermediate⏱ 2 h 🟢 FreeSCS-C03SAA-C03DVA-C03

Assumes: .NET 10 LTS · ASP.NET Core 10 · AWS SDK for .NET v4 · AWS CLI v2 · OpenSSL 3.x · Region us-east-1. Verified against official sources on 2026-11-17.

Learning objectives

By the end of this lesson you can:

  • Explain what a certificate, a certificate authority (CA), a trust store and a TLS handshake are, and what mutual TLS (mTLS) adds.
  • Request a public certificate from AWS Certificate Manager (ACM) with DNS validation and explain why its renewal is automatic, and when it is not.
  • Decide between ACM public certificates, exportable public certificates and AWS Private CA (general-purpose vs short-lived mode), with real prices.
  • Choose a strict TLS security policy on an Application Load Balancer (ALB) and on API Gateway, and avoid the default that IaC tools silently apply.
  • Configure mTLS on an ALB (verify or passthrough mode) and on an API Gateway custom domain, and know the limits of each.
  • Build a free, local mTLS lab: an OpenSSL CA, an ASP.NET Core API that demands client certificates, and a .NET HttpClient that presents one.

Prerequisites

Why this matters in banking

Two incidents every bank has had at least once:

  1. The expired certificate. At 00:00 on a Saturday the certificate on the Open Banking API expires. Every third-party provider's calls fail with TLS errors. Nobody owned the renewal because "the infrastructure team did it last year". Customer payments fail for six hours and the incident goes to the regulator as an operational-resilience event.
  2. The trusted network that was not. An internal payments service accepts any HTTPS call from inside the data centre, because "it is on the private network". An attacker who compromises a reporting server can call it directly and initiate transfers.

Certificates fix both when they are managed properly: automatic renewal removes the human calendar reminder, and mutual TLS means every caller proves who it is with a certificate, not with its IP address. Open Banking ecosystems (for example the UK Open Banking standards and FAPI profiles) already require mTLS between banks and third-party providers, so you will meet it in your daily work.

The idea in plain language

TLS (Transport Layer Security) is the protocol behind https://. When a client connects, the server presents a certificate: a small signed document that says "this public key belongs to api.harbourline.example". The certificate is signed by a certificate authority (CA) that the client already trusts. The client checks the signature, the name and the dates, then both sides agree on session keys and everything after that is encrypted and tamper-evident.

A trust store is the list of CA certificates you are willing to believe. Your browser and Windows ship with a public trust store. Inside a bank you also run a private CA, whose root certificate is only in your own trust stores.

In normal TLS only the server proves its identity. In mutual TLS (mTLS) the server also asks the client for a certificate and checks it against its trust store. Both sides are authenticated before a single byte of the HTTP request is read.

Analogy: TLS is the branch counter with a glass screen and a name badge on the cashier: you know you are talking to the real bank and nobody can overhear. mTLS is the cash-in-transit handover: the guard checks the courier's ID card against the approved list and the courier checks the guard's ID before any money moves. The CA is the agency that prints ID cards; the trust store is the list of agencies you accept.

Three words you will see constantly:

TermMeaning
Leaf (end-entity) certificateThe certificate of the server or client itself
Intermediate CAA CA signed by the root, which signs leaves. Roots stay offline; intermediates do the daily work
ChainLeaf → intermediate(s) → root. A validator needs the whole path

What problem the AWS services solve

AWS Certificate Manager (ACM)

ACM issues, stores and renews certificates and deploys them to integrated services: Elastic Load Balancing, CloudFront, API Gateway, App Runner (closed to new customers), AWS Amplify and others. You never see the private key of a normal ACM public certificate; it stays inside AWS.

Key facts, checked on 2026-11-17:

FactDetail
PricePublic certificates used with integrated services are free
ValidationDNS validation (recommended; a CNAME record in your zone). Email validation is being deprecated. HTTP validation exists only for CloudFront distribution tenants
ValidityACM public certificates are now valid for 198 days (the industry is shortening certificate lifetimes; ACM moved from 395 days)
RenewalManaged and automatic for DNS-validated certificates that are in use (associated with a service or exported). Imported certificates are never renewed by ACM
RegionCertificates are regional. CloudFront only uses certificates from us-east-1
AlgorithmsACM can request RSA 2048, ECDSA P-256 and ECDSA P-384 certificates
ARNStays the same after renewal, so nothing needs redeploying

Exportable public certificates (launched June 2025) let you mark a new public certificate as exportable and download it, with its private key, to use on EC2, on-premises or in containers. They cost USD 7 per fully qualified domain name and USD 79 per wildcard name, charged at issue and again at each renewal. Previously issued certificates cannot be made exportable. Control who may request them with IAM.

AWS Private CA

AWS Private CA runs a managed private certificate authority for you: the CA key lives in FIPS-validated HSMs that AWS operates. Use it for internal service names, mTLS client certificates, devices and anything that should never be trusted by the public internet.

ModeMonthly price per CAPer certificateCertificate lifetime
General-purposeUSD 400USD 0.75 (first 1,000/month), USD 0.35 (1,001–10,000), USD 0.001 aboveAny
Short-lived certificate modeUSD 50USD 0.058Up to 7 days

The first private CA in each Region has a 30-day free trial of the CA charge (certificates issued are still billed). Delete the CA before the trial ends if you are only experimenting. For this course Private CA is design-only: the local OpenSSL CA gives you the same learning for free.

Short-lived certificates are a security feature, not just a discount

A 1–7 day certificate does not need revocation checking in practice: if a key leaks, it stops working within days. Services that can automate renewal (service meshes, ECS tasks fetching certs at start-up) are good candidates. Long-lived partner certificates still need general-purpose mode and a revocation process.

Where TLS and mTLS can terminate on AWS

ServiceTLS terminationmTLS supportNotes
ALBYes, ACM certificate on an HTTPS listenerVerify mode (ALB validates against a trust store, optional CRLs) or passthrough mode (ALB forwards the chain in a header, your app validates)Session resumption is not supported with mTLS
NLBTLS listener, or TCP passthroughPass TLS straight through to targets that do mTLS themselvesUseful when the app must see the raw handshake
API Gateway RESTCustom domain with ACM certificateYes, on a Regional custom domain with a trust store PEM file in S3 and the TLS_1_2 policyNot for private APIs; not with the newer enhanced policies; no revocation check (use a Lambda authorizer)
API Gateway HTTP APICustom domainYes (Regional custom domain)Only the TLS_1_2 policy
CloudFrontViewer certificate from us-east-1⚠ VERIFY current viewer mTLS support before designing on itOrigin connections can be HTTPS-only
Your container/EC2Kestrel, nginx, EnvoyAnything you implementYou own patching, rotation and key storage

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
App Service Managed Certificate / Front Door managed certsACM public certificateFree and auto-renewed on AWS too, but only while attached to an integrated service; private key never exported unless you pay for an exportable cert
Key Vault certificates (with auto-renew via a CA integration)ACM (managed) + ACM import for third-party certsACM does not renew imported certificates; Key Vault can with an integrated CA
Active Directory Certificate Services (AD CS)AWS Private CAFully managed, HSM-backed, priced per CA per month; no Windows servers to patch
Application Gateway mTLS / Front DoorALB mTLS (verify/passthrough) or API Gateway mTLSALB trust store is a PEM bundle in S3 plus optional CRLs
RequireClientCertificate in IIS/KestrelSame in Kestrel; or let the ALB verifyDecide where verification happens and pass identity safely to the app
TLS settings on App Service ("Minimum TLS version")Security policy on each listener/domainNamed policies; IaC defaults can be weaker than console defaults

Architecture

Security-boundary view. There are three trust decisions in this picture, and each one belongs to a different owner:

  • Security of the cloud (AWS): ACM's CA infrastructure, HSMs behind Private CA, the TLS implementation on ALB and API Gateway, patching of those fleets.
  • Security in the cloud (Harbourline): which CAs you trust, which certificates you issue to whom, the security policy you select, disabling the default execute-api endpoint, revocation, mapping a client certificate to a business identity, and monitoring expiry of anything ACM does not renew.

Step-by-step implementation

This lesson has two tracks. Track A is free and local: you build a CA and an mTLS-protected API on your laptop. Track B shows the AWS configuration; deploy it only if you have a domain in Route 53 and accept a small ALB charge.

Create a lab folder and a local CA (Track A, free)

Open Git Bash (it includes OpenSSL). Git Bash rewrites arguments that start with /, which breaks OpenSSL's -subj "/CN=..."; the MSYS_NO_PATHCONV=1 line prevents that.

make-ca.sh
#!/usr/bin/env bash
# Builds a throwaway CA, one server certificate and one client certificate.
# Learning only: keys are unencrypted on disk and the CA lives for 30 days.
set -euo pipefail
export MSYS_NO_PATHCONV=1
mkdir -p certs && cd certs

# 1. Root CA: an ECDSA P-256 key and a self-signed certificate marked CA:TRUE
openssl req -x509 -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -keyout ca.key -out ca.crt -days 30 \
  -subj "/O=Harbourline Learn/CN=Harbourline Learn Partner CA" \
  -addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
  -addext "keyUsage=critical,keyCertSign,cRLSign"

# 2. Server certificate for localhost (serverAuth only)
cat > server.ext <<'EOF'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
extendedKeyUsage=serverAuth
subjectAltName=DNS:localhost
EOF
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -keyout server.key -out server.csr -subj "/CN=localhost"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out server.crt -days 7 -sha256 -extfile server.ext

# 3. Client certificate for a fictional partner (clientAuth only)
cat > client.ext <<'EOF'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
extendedKeyUsage=clientAuth
EOF
openssl req -new -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -keyout client.key -out client.csr \
  -subj "/O=Acme Payments Ltd (fictional)/CN=tpp-acme-payments"
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -out client.crt -days 7 -sha256 -extfile client.ext

# 4. Bundle the client key + cert as PKCS#12 for .NET (password from env var)
openssl pkcs12 -export -out client.pfx -inkey client.key -in client.crt \
  -passout env:HL_CLIENT_PFX_PASSWORD

# 5. Show what we built
openssl x509 -in client.crt -noout -subject -issuer -dates -ext extendedKeyUsage
openssl verify -CAfile ca.crt server.crt client.crt

Run it:

export HL_CLIENT_PFX_PASSWORD='learn-only-not-a-secret'
bash make-ca.sh

Expected last lines: server.crt: OK and client.crt: OK. No Git Bash? Run the same script in Docker: docker run --rm -v "$PWD:/work" -w /work -e HL_CLIENT_PFX_PASSWORD alpine:3.22 sh -c "apk add --no-cache openssl bash >/dev/null && bash make-ca.sh".

Build an API that requires client certificates

Create the server project (complete code is in Complete code):

dotnet new web -n Harbourline.Partners.MtlsApi -f net10.0
cd Harbourline.Partners.MtlsApi
dotnet add package Microsoft.AspNetCore.Authentication.Certificate --version 10.0.15

Kestrel is told to require a client certificate during the handshake, and the certificate authentication handler validates the chain against only our lab CA (not the Windows trust store). An authorization policy then maps the certificate subject to a known partner.

Call it with a client certificate from .NET

Create a console app Harbourline.Partners.MtlsClient that loads client.pfx, presents it, and validates the server certificate against the same lab CA. Run the server, then the client. You should see 200 with the partner name, then a second call without a certificate failing during the TLS handshake.

Prove the negative cases

These are the tests a bank's security reviewer will ask for:

# No client certificate: handshake fails (curl error 56 or an alert "certificate required")
curl --cacert certs/ca.crt https://localhost:5443/partner/whoami

# Correct client certificate: 200 OK
curl --cacert certs/ca.crt --cert certs/client.crt --key certs/client.key \
  https://localhost:5443/partner/whoami

# A certificate from a different CA: rejected (403 from the auth handler)
MSYS_NO_PATHCONV=1 openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
  -keyout rogue.key -out rogue.crt -days 1 -subj "/CN=tpp-acme-payments"
curl --cacert certs/ca.crt --cert rogue.crt --key rogue.key \
  https://localhost:5443/partner/whoami

The rogue certificate has the same name as the real partner. It is rejected because the signature chain does not lead to the trusted CA. That is the whole point: names are cheap, signatures are not.

Map the design to AWS (Track B)

On AWS you can move the verification out of your code:

  • ALB verify mode: upload ca.crt (or your Private CA root and intermediates) to S3 as a PEM bundle, create a trust store, attach it to the HTTPS listener with mode verify. The ALB rejects untrusted clients and forwards X-Amzn-Mtls-Clientcert-Subject, -Issuer, -Serial-Number, -Validity and -Leaf headers to targets.
  • ALB passthrough mode: the ALB accepts any certificate and forwards the whole chain in X-Amzn-Mtls-Clientcert. Your app must validate it, exactly like the local lab. Use passthrough only when you need logic the ALB cannot do.
  • API Gateway: a Regional custom domain with --mutual-tls-authentication truststoreUri=s3://... and the TLS_1_2 security policy, plus disable the default execute-api endpoint, otherwise callers can bypass mTLS entirely.

AWS Console instructions

Request a public certificate. Console → Certificate Manager (check the Region selector: us-east-1 for CloudFront) → Request → Request a public certificate → enter api.learn.example.com (use a domain you control) → Validation method: DNS validation → Key algorithm: ECDSA P 256 → leave Allow export disabled (exporting costs money) → add the four mandatory tags → Request. Open the certificate → Create records in Route 53 if the zone is in Route 53, otherwise copy the CNAME name and value into your DNS provider. Status changes from Pending validation to Issued within minutes.

Create an ALB trust store. Console → EC2 → Load Balancing → Trust Stores → Create trust store → name hl-m05-partner-trust → CA certificate bundle: the S3 URI of your PEM file (bucket with Block Public Access and SSE) → optionally add a certificate revocation list → Create.

Turn on mTLS on a listener. Console → EC2 → Load balancers → your ALB → Listeners and rules → select the HTTPS:443 listener → Edit listener → Secure listener settings → Security policy: ELBSecurityPolicy-TLS13-1-2-Res-PQ-2025-09 (the console default) → Client certificate handling: Mutual authentication (mTLS) → Verify with trust store → choose hl-m05-partner-trust → optionally Advertise trust store CA subject names → Save changes.

API Gateway mTLS. Console → API Gateway → Custom domain names → Create → domain partners.learn.example.com → Regional → Minimum TLS version / security policy: TLS 1.2 → Mutual TLS authentication: on, Truststore URI s3://hl-m05-truststore-<account-id>/truststore.pem → ACM certificate → Create. Then, on the API: Settings → Default endpoint → Disabled.

AWS CLI

# Request a DNS-validated ECDSA certificate. Free while not exportable.
aws acm request-certificate \
  --domain-name api.learn.example.com \
  --validation-method DNS \
  --key-algorithm EC_prime256v1 \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-tls Key=Environment,Value=learn Key=Owner,Value=alex \
  --profile learn-sandbox --region us-east-1

# Show the CNAME record ACM wants you to create for validation
aws acm describe-certificate --certificate-arn "$CERT_ARN" \
  --query "Certificate.DomainValidationOptions[0].ResourceRecord" \
  --profile learn-sandbox --region us-east-1

# Find certificates expiring soon (renewal problems show up here first)
aws acm list-certificates --certificate-statuses ISSUED \
  --query "CertificateSummaryList[].{Domain:DomainName,NotAfter:NotAfter,InUse:InUse,Renewal:RenewalEligibility}" \
  --profile learn-sandbox --region us-east-1

# Upload the CA bundle and create an ALB trust store from it
aws s3 cp certs/ca.crt "s3://hl-m05-truststore-${ACCOUNT_ID}/partner-ca.pem" \
  --profile learn-sandbox
aws elbv2 create-trust-store --name hl-m05-partner-trust \
  --ca-certificates-bundle-s3-bucket "hl-m05-truststore-${ACCOUNT_ID}" \
  --ca-certificates-bundle-s3-key partner-ca.pem \
  --profile learn-sandbox --region us-east-1

# Switch an HTTPS listener to a strict TLS 1.3/1.2 policy and mTLS verify mode
aws elbv2 modify-listener --listener-arn "$LISTENER_ARN" \
  --ssl-policy ELBSecurityPolicy-TLS13-1-2-Res-PQ-2025-09 \
  --mutual-authentication "Mode=verify,TrustStoreArn=${TRUST_STORE_ARN}" \
  --profile learn-sandbox --region us-east-1

# API Gateway: Regional custom domain that requires client certificates
aws apigateway create-domain-name \
  --domain-name partners.learn.example.com \
  --regional-certificate-arn "$CERT_ARN" \
  --endpoint-configuration types=REGIONAL \
  --security-policy TLS_1_2 \
  --mutual-tls-authentication "truststoreUri=s3://hl-m05-truststore-${ACCOUNT_ID}/partner-ca.pem" \
  --profile learn-sandbox --region us-east-1

# Close the bypass: disable the default execute-api endpoint of the REST API
aws apigateway update-rest-api --rest-api-id "$API_ID" \
  --patch-operations op=replace,path=/disableExecuteApiEndpoint,value='True' \
  --profile learn-sandbox --region us-east-1

AWS Private CA (design-only; this command starts a USD 50/month charge after the free trial):

# DO NOT RUN unless you intend to pay. Shown so you recognise the shape.
# aws acm-pca create-certificate-authority \
#   --certificate-authority-configuration file://ca-config.json \
#   --certificate-authority-type SUBORDINATE \
#   --usage-mode SHORT_LIVED_CERTIFICATE \
#   --tags Key=Project,Value=cea-lab

Infrastructure as Code

MtlsListenerStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AWS.S3;
using Constructs;

namespace Harbourline.Security.Infra;

public sealed class MtlsListenerStack : Stack
{
    public MtlsListenerStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        var vpc = Vpc.FromLookup(this, "Vpc", new VpcLookupOptions { Tags = new Dictionary<string, string> { ["Name"] = "hl-m02-vpc" } });

        // Bucket holding the CA bundle: private, encrypted, TLS-only, versioned (trust store versions)
        var trustBucket = new Bucket(this, "TrustBucket", new BucketProps
        {
            BlockPublicAccess = BlockPublicAccess.BLOCK_ALL,
            Encryption = BucketEncryption.S3_MANAGED,
            EnforceSSL = true,
            Versioned = true,
            RemovalPolicy = RemovalPolicy.DESTROY,   // learning shortcut
            AutoDeleteObjects = true                 // learning shortcut
        });

        var trustStore = new TrustStore(this, "PartnerTrust", new TrustStoreProps
        {
            Bucket = trustBucket,
            Key = "partner-ca.pem",               // upload this object before deploying the listener
            TrustStoreName = "hl-m05-partner-trust"
        });

        var cert = Certificate.FromCertificateArn(this, "Cert", (string)Node.TryGetContext("certificateArn"));

        var alb = new ApplicationLoadBalancer(this, "Alb", new ApplicationLoadBalancerProps
        {
            Vpc = vpc,
            InternetFacing = false,                 // internal: service-to-service mTLS
            DropInvalidHeaderFields = true
        });

        alb.AddListener("Https", new BaseApplicationListenerProps
        {
            Port = 443,
            Protocol = ApplicationProtocol.HTTPS,
            Certificates = new IListenerCertificate[] { ListenerCertificate.FromCertificateManager(cert) },
            // Explicit policy: IaC defaults to ELBSecurityPolicy-2016-08 if you leave this out
            SslPolicy = SslPolicy.TLS13_12_RES_PQ,
            MutualAuthentication = new MutualAuthentication
            {
                MutualAuthenticationMode = MutualAuthenticationMode.VERIFY,
                TrustStore = trustStore,
                IgnoreClientCertificateExpiry = false,
                AdvertiseTrustStoreCaNames = true
            },
            DefaultAction = ListenerAction.FixedResponse(200, new FixedResponseOptions
            {
                ContentType = "text/plain",
                MessageBody = "mTLS OK"
            })
        });

        foreach (var (k, v) in new Dictionary<string, string>
                 { ["Project"] = "cea-lab", ["Lab"] = "m05-tls", ["Environment"] = "learn", ["Owner"] = "alex" })
            Amazon.CDK.Tags.Of(this).Add(k, v);
    }
}

Complete code

Server: ASP.NET Core API that requires client certificates

Harbourline.Partners.MtlsApi.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Partners.MtlsApi</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Certificate" Version="10.0.15" />
  </ItemGroup>
</Project>
Program.cs
using System.Security.Authentication;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authentication.Certificate;
using Microsoft.AspNetCore.Server.Kestrel.Https;

var builder = WebApplication.CreateBuilder(args);
var certDir = builder.Configuration["CertDir"] ?? "../certs";

// Trust anchor: ONLY the lab partner CA, never the machine store.
var partnerCa = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(certDir, "ca.crt"));

// Server certificate from PEM. Re-import as PKCS#12 so SslStream on Windows
// gets a persisted key handle (ephemeral PEM keys fail on Windows SChannel).
using var pemServer = X509Certificate2.CreateFromPemFile(
    Path.Combine(certDir, "server.crt"), Path.Combine(certDir, "server.key"));
var serverCert = X509CertificateLoader.LoadPkcs12(pemServer.Export(X509ContentType.Pkcs12), password: null);

// Allow-list: certificate subject CN -> partner id. In production this lives in a
// partner registry (DynamoDB) and is keyed on issuer + serial or a thumbprint.
var knownPartners = new Dictionary<string, string>(StringComparer.Ordinal)
{
    ["tpp-acme-payments"] = "PARTNER-0001"
};

builder.WebHost.ConfigureKestrel(kestrel =>
{
    kestrel.AddServerHeader = false;
    kestrel.ListenLocalhost(5443, listen => listen.UseHttps(https =>
    {
        https.ServerCertificate = serverCert;
        https.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13;
        // Handshake fails if the client sends no certificate at all.
        https.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
        // Let the authentication handler (below) do the chain validation,
        // so we can use a custom trust store and log useful reasons.
        https.AllowAnyClientCertificate();
    }));
});

builder.Services
    .AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
    .AddCertificate(options =>
    {
        options.AllowedCertificateTypes = CertificateTypes.Chained;   // no self-signed clients
        options.ChainTrustValidationMode = X509ChainTrustMode.CustomRootTrust;
        options.CustomTrustStore = new X509Certificate2Collection { partnerCa };
        options.ValidateCertificateUse = true;                        // requires clientAuth EKU
        options.ValidateValidityPeriod = true;
        options.RevocationMode = X509RevocationMode.NoCheck;          // ⚠ learning shortcut, see Security considerations
        options.Events = new CertificateAuthenticationEvents
        {
            OnCertificateValidated = ctx =>
            {
                var cn = ctx.ClientCertificate.GetNameInfo(X509NameType.SimpleName, forIssuer: false);
                if (!knownPartners.TryGetValue(cn, out var partnerId))
                {
                    ctx.Fail($"Certificate subject '{cn}' is not an onboarded partner.");
                    return Task.CompletedTask;
                }
                var claims = new[]
                {
                    new Claim("partner_id", partnerId, ClaimValueTypes.String, ctx.Options.ClaimsIssuer),
                    new Claim("cert_thumbprint", ctx.ClientCertificate.Thumbprint, ClaimValueTypes.String, ctx.Options.ClaimsIssuer)
                };
                ctx.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ctx.Scheme.Name));
                ctx.Success();
                return Task.CompletedTask;
            },
            OnAuthenticationFailed = ctx =>
            {
                ctx.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>()
                    .CreateLogger("mtls").LogWarning("Client certificate rejected: {Reason}", ctx.Exception.Message);
                return Task.CompletedTask;
            }
        };
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("Partner", p => p.RequireClaim("partner_id"));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/partner/whoami", (ClaimsPrincipal user) => Results.Ok(new
{
    partnerId = user.FindFirstValue("partner_id"),
    certificateThumbprint = user.FindFirstValue("cert_thumbprint")
})).RequireAuthorization("Partner");

app.Run();

Client: HttpClient that presents a certificate

Harbourline.Partners.MtlsClient/Program.cs
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

var certDir = args.Length > 0 ? args[0] : "../certs";
var pfxPassword = Environment.GetEnvironmentVariable("HL_CLIENT_PFX_PASSWORD")
    ?? throw new InvalidOperationException("Set HL_CLIENT_PFX_PASSWORD first.");

var labCa = X509CertificateLoader.LoadCertificateFromFile(Path.Combine(certDir, "ca.crt"));
using var clientCert = X509CertificateLoader.LoadPkcs12FromFile(
    Path.Combine(certDir, "client.pfx"), pfxPassword);

var handler = new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(5),
    SslOptions = new SslClientAuthenticationOptions
    {
        EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
        ClientCertificates = new X509CertificateCollection { clientCert },
        // Lab server cert is signed by our own CA, so validate against it explicitly.
        // With a public ACM certificate you would NOT set this callback at all.
        RemoteCertificateValidationCallback = (_, certificate, _, errors) =>
        {
            if (certificate is null) return false;
            if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch)) return false;

            using var chain = new X509Chain();
            chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
            chain.ChainPolicy.CustomTrustStore.Add(labCa);
            chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;   // ⚠ learning shortcut
            return chain.Build(new X509Certificate2(certificate));
        }
    }
};

using var http = new HttpClient(handler) { BaseAddress = new Uri("https://localhost:5443") };
var response = await http.GetAsync("/partner/whoami");
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");

Run:

# terminal 1
dotnet run --project Harbourline.Partners.MtlsApi -- --CertDir ../certs
# terminal 2
export HL_CLIENT_PFX_PASSWORD='learn-only-not-a-secret'
dotnet run --project Harbourline.Partners.MtlsClient -- ../certs

Expected output:

200 {"partnerId":"PARTNER-0001","certificateThumbprint":"3F0C…"}

Code explained line by line

Server

  1. X509CertificateLoader.LoadCertificateFromFile(...) — the .NET 9+ loader API. It replaces the obsolete new X509Certificate2(path) constructors and refuses to guess file formats, which closes a class of parsing bugs.
  2. X509Certificate2.CreateFromPemFile(crt, key) then LoadPkcs12(pem.Export(...)) — combines the PEM certificate and key, then re-imports them. On Windows, SChannel cannot use the ephemeral key that CreateFromPemFile produces; the round-trip gives it a usable key. On Linux containers the extra step is harmless.
  3. knownPartners — certificate validity proves "the Partner CA issued this"; it does not prove "this partner is allowed in". Always keep an allow-list (in production, issuer + serial number or SHA-256 thumbprint in a partner registry).
  4. kestrel.AddServerHeader = false — avoid advertising the server technology.
  5. https.SslProtocols = Tls12 | Tls13 — never negotiate TLS 1.0/1.1.
  6. ClientCertificateMode.RequireCertificate — the TLS handshake itself fails without a client certificate, so unauthenticated callers never reach routing or middleware.
  7. AllowAnyClientCertificate() — tells Kestrel not to run the OS chain check, because the OS store does not contain our lab CA. The authentication handler performs the real validation. Do not use this line without the handler.
  8. AllowedCertificateTypes = CertificateTypes.Chained — rejects self-signed client certificates outright.
  9. ChainTrustValidationMode = CustomRootTrust + CustomTrustStore — the chain must end at our CA, not at any CA Windows happens to trust. This is the most important line in the file.
  10. ValidateCertificateUse = true — the certificate must carry the clientAuth extended key usage. A server certificate stolen from elsewhere cannot be replayed as a client certificate.
  11. RevocationMode = NoCheck — a learning shortcut: our lab CA publishes no CRL. In production use Online with a reachable CRL distribution point, or short-lived certificates.
  12. OnCertificateValidated — runs after the chain is valid. It maps the subject to a partner, fails unknown subjects, and builds a ClaimsPrincipal with partner_id and the thumbprint for audit logging.
  13. OnAuthenticationFailed — logs why a certificate was rejected (expired, wrong issuer). Without this, mTLS failures are painful to debug.
  14. AddPolicy("Partner", p => p.RequireClaim("partner_id")) and .RequireAuthorization("Partner") — authentication says who you are; authorization decides what you can call. Per-endpoint policies can later check scopes per partner.

Client

  1. HL_CLIENT_PFX_PASSWORD from the environment — no secrets in code. In AWS, a workload would fetch its certificate and key from Secrets Manager, or receive a short-lived certificate from Private CA at start-up.
  2. LoadPkcs12FromFile — loads the client key and certificate together.
  3. SocketsHttpHandler with SslClientAuthenticationOptions — the modern way to configure TLS for HttpClient. PooledConnectionLifetime makes sure DNS changes and certificate rotation are picked up.
  4. ClientCertificates = { clientCert } — the certificate offered when the server asks for one.
  5. RemoteCertificateValidationCallback — only needed because the lab server uses a private CA. It still rejects name mismatches and builds the chain against the lab CA only. Never write => true here; that disables server authentication completely and is a classic finding in bank code reviews.
  6. In production with IHttpClientFactory: register a named client with ConfigurePrimaryHttpMessageHandler(() => handler) so connection pooling and certificate loading happen once.

Security considerations

⚠ Learning shortcut — not for production

The local CA key (ca.key) sits unencrypted on your disk, certificates are not revocable, and the client PFX password is an environment variable. In production: keep CA keys in AWS Private CA or an HSM (never on a laptop), use an offline root with an online intermediate, issue client certificates through an onboarding workflow with dual control, publish CRLs or use short-lived certificates, and store private keys in Secrets Manager encrypted with a KMS customer managed key, or better, never let them leave the workload (CSR generated in the container, signed by Private CA).

  • Disable the bypass. API Gateway mTLS protects the custom domain only. If the default execute-api endpoint is enabled, callers can skip mTLS. The same applies to an ALB with an extra HTTP listener, or a target group reachable directly from inside the VPC: restrict target security groups to the ALB's security group.
  • Header spoofing. In ALB verify mode your app trusts X-Amzn-Mtls-Clientcert-* headers. That is safe only if the app can be reached exclusively through the ALB. Set DropInvalidHeaderFields on the ALB and lock the target security group.
  • Pick the policy explicitly. The ALB console default is ELBSecurityPolicy-TLS13-1-2-Res-PQ-2025-09, but the CLI, CloudFormation and CDK default is still ELBSecurityPolicy-2016-08, which allows TLS 1.0. Always set SslPolicy in IaC. A Security Hub CSPM control also flags weak ELB policies.
  • API Gateway trade-off. The enhanced policies such as SecurityPolicy_TLS13_1_3_2025_09 (TLS 1.3 only, with endpoint access mode STRICT) cannot be combined with mTLS today; mTLS requires TLS_1_2. Document this decision.
  • Revocation. API Gateway does not check revocation. Use a Lambda authorizer that checks the certificate serial against a revocation list, or prefer the ALB, which supports CRLs in trust stores.
  • Expiry monitoring. ACM publishes the DaysToExpiry metric and EventBridge events for certificates approaching expiry. Alarm on imported certificates especially, since ACM never renews them.
  • Logging. ALB connection logs record TLS versions, ciphers and client certificate details. API Gateway access logs can include $context.identity.clientCert.* and $context.tlsVersion. Treat certificate subjects as personal data if they contain names of individuals.
  • Responsibility split. AWS operates ACM and Private CA infrastructure (security of the cloud). Harbourline decides which CAs are trusted, who gets certificates, which policies are allowed, and proves it to auditors (security in the cloud). None of this makes an API "compliant" with Open Banking, PSD2 or PCI DSS on its own; your security architecture and compliance teams must review the full design.

Banking use case

Harbourline Bank exposes Open Banking-style account information APIs to licensed third-party providers (TPPs). The design:

  1. Each TPP is onboarded by the partner team after legal checks. The PKI team issues a client certificate from the Harbourline Partner CA (an AWS Private CA subordinate in general-purpose mode, chained to an offline root). Onboarding records issuer, serial and expiry in a partner registry.
  2. TPPs call partners.api.harbourline.example, an API Gateway Regional custom domain with mTLS. The default execute-api endpoint is disabled.
  3. A Lambda authorizer checks the certificate serial against the registry (not revoked, partner active) and adds partner_id to the request context. OAuth 2.0 access tokens bound to the certificate (FAPI-style certificate-bound tokens) are checked as well, so a stolen token alone is useless.
  4. Internally, the Accounts API calls the Payments Service through an internal ALB in mTLS verify mode. ECS tasks receive short-lived certificates (24 hours) from a Private CA in short-lived mode, issued at task start.
  5. EventBridge rules on ACM expiry events open a ticket 45 days before any certificate the bank cannot auto-renew expires.

Compliance teams review the design against the bank's interpretation of the Open Banking standards; architecture does not "make" the bank compliant.

Common mistakes

  • Leaving the ALB on the IaC default policy → TLS 1.0 is accepted, a pen test flags it → always set SslPolicy explicitly.
  • Using email validation → renewals stall when nobody clicks the email → use DNS validation and keep the CNAME record forever.
  • Deleting the validation CNAME after issue → the next automatic renewal fails silently → treat validation records as permanent infrastructure.
  • Importing a certificate and assuming ACM renews it → outage at expiry → monitor DaysToExpiry on imported certificates.
  • Trusting the OS store for client certificates → any publicly issued certificate is accepted as a "partner" → always use a dedicated trust store/CA.
  • Validating the chain but not the identity → any certificate from the CA can call any partner endpoint → map certificate to partner and authorize per partner.
  • RemoteCertificateValidationCallback = (_, _, _, _) => true → turns HTTPS into unauthenticated encryption, open to man-in-the-middle → validate against a specific root, or do not override.
  • Forgetting the default execute-api endpoint → mTLS can be bypassed → disable it.

Troubleshooting

SymptomLikely causeFix
OpenSSL in Git Bash: Subject does not start with '/' or a path like C:/Program Files/Git/CN=...MSYS path conversion of -subjexport MSYS_NO_PATHCONV=1 before running OpenSSL
ACM certificate stuck in Pending validationCNAME missing, wrong zone, or CAA record blocks AmazonCheck the record with nslookup -type=CNAME; add a CAA record allowing amazon.com if you use CAA
ACM status Ineligible for renewalCertificate not in use, or importedAttach it to a resource, or replace imported certs before expiry
Kestrel on Windows: No credentials are available in the security packageEphemeral PEM keyRe-import as PKCS#12 as shown in the server code
curl: (56) ... alert certificate requiredClient sent no certificatePass --cert and --key; in .NET check ClientCertificates
403 and log Client certificate rejected: ... chainWrong CA, missing intermediate, or self-signed clientRebuild with openssl verify -CAfile ca.crt client.crt; include intermediates
403 not an onboarded partnerSubject CN not in the allow-listAdd the partner or fix the CN
The remote certificate is invalid according to the validation procedure in the clientServer cert not trusted by the client callback, or name mismatchUse localhost as SAN; load the right ca.crt
ALB returns connection reset for some clients after enabling mTLSClients lack a certificate from the trust store CACheck ALB connection logs; use Advertise trust store CA subject names to help clients pick the right cert
API Gateway warnings when creating the mTLS domainInvalid or expired certificate in truststore.pemDecode each certificate with openssl x509 -text -noout; upload a new version and update the domain

Cost and cleanup

  • Track A (local): free.
  • ACM public certificates: free unless you enable export (USD 7 per FQDN, USD 79 per wildcard, per issue and renewal).
  • ALB: billed per hour plus LCUs (roughly USD 0.02–0.03 per hour in us-east-1 ⚠ VERIFY current price). Trust stores add a per-hour charge ⚠ VERIFY. Deploy, test and destroy within one hour.
  • API Gateway: pay per request; a few test calls cost fractions of a cent. A custom domain needs a domain you own (Route 53 hosted zone USD 0.50 per month).
  • AWS Private CA: design-only here (USD 50–400 per CA per month after the 30-day trial).
# Local
rm -rf certs rogue.key rogue.crt

# AWS (only if you created them)
aws elbv2 modify-listener --listener-arn "$LISTENER_ARN" --mutual-authentication Mode=off --profile learn-sandbox
aws elbv2 delete-trust-store --trust-store-arn "$TRUST_STORE_ARN" --profile learn-sandbox
aws apigateway delete-domain-name --domain-name partners.learn.example.com --profile learn-sandbox
aws acm delete-certificate --certificate-arn "$CERT_ARN" --profile learn-sandbox
aws s3 rm "s3://hl-m05-truststore-${ACCOUNT_ID}" --recursive --profile learn-sandbox
aws s3api delete-bucket --bucket "hl-m05-truststore-${ACCOUNT_ID}" --profile learn-sandbox
# or: cdk destroy / terraform destroy

# Confirm nothing tagged for the course remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --query "ResourceTagMappingList[].ResourceARN" --profile learn-sandbox

An ACM certificate cannot be deleted while it is attached to a listener or domain; remove those first.

Exercises

  • 🟢 Guided: Build the local CA, run the API and client, and capture four outcomes: no certificate, the valid partner certificate, a rogue self-signed certificate with the same name, and the server certificate (server.crt + server.key, signed by the same CA) presented as a client certificate.
  • 🟡 Challenge: Add an intermediate CA (root → intermediate → client). Make the server trust only the root, and make the client send the intermediate in its chain. Then change the server so that a certificate from a second intermediate under the same root is rejected (hint: pin the issuing intermediate in OnCertificateValidated).
  • 🔴 Live problem: A TPP reports that since Monday "about 30% of calls fail with TLS errors" against your API Gateway mTLS domain. Your team rotated the partner CA intermediate last Friday and uploaded a new truststore.pem. No alarms fired. Write the investigation plan and the fix, and the control that would have caught it before Monday.

Assignment

Produce a one-page certificate inventory and policy for the Harbourline Accounts API: every certificate (public, partner, internal), who issues it, lifetime, renewal method, where the key lives, who is alerted at expiry, and the TLS policy on each endpoint. Commit it to your portfolio repository with the local mTLS code.

Solutions

Knowledge check

Interview questions

  • "How would you secure service-to-service calls inside a VPC?" — Do not rely on network location alone. Use mTLS with certificates from a private CA (AWS Private CA, short-lived certificates where automation allows), verify at an internal ALB or in the service, authorize based on the certificate identity, and keep IAM/SigV4 for AWS APIs. Combine with security groups for defence in depth.
  • "What is the difference between ACM and AWS Private CA?" — ACM manages certificates (issue, renew, deploy to integrated services; public certificates free). Private CA is a managed certificate authority for private PKI, billed per CA per month; ACM can issue and renew private certificates from it.
  • "A partner's certificate was compromised. What do you do?" — Revoke it at the CA (publish CRL), remove it from the partner registry so the authorizer denies it immediately, check logs for calls made with it since the suspected compromise, issue a replacement through the onboarding process, and notify per the incident process.
  • "Why are short-lived certificates attractive?" — They limit the damage of a leaked key to hours or days and reduce dependence on revocation checking, which clients often skip or fail open on.

Certification practice

Completion checklist

  • I can explain TLS, mTLS, CA, chain and trust store in two sentences each
  • I built the local CA and observed all four mTLS outcomes
  • I can state ACM's validity, renewal conditions and export pricing
  • I know the console vs IaC default ALB security policy
  • I know why the default execute-api endpoint must be disabled with API Gateway mTLS
  • I deleted local keys and any AWS resources I created

Key takeaways

  • ACM public certificates are free, valid for 198 days and auto-renew only when DNS-validated and in use; imported certificates are your problem.
  • AWS Private CA is for private PKI; short-lived mode (USD 50/month, 7-day certificates) is cheaper and safer when you can automate.
  • mTLS authenticates the caller cryptographically, but you still need an allow-list, authorization and revocation.
  • Always set TLS security policies explicitly in IaC; the console default is stronger than the API default.
  • Close every bypass: default API endpoints, extra listeners and directly reachable targets.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page