Implementing Zero-Trust Architecture in .NET APIs with Certificate-Based Authentication
Our core API — handling tens of thousands of financial transactions per hour — suddenly began rejecting requests. Our logs were littered with expired JWT tokens, tracing back to a clock drift issue between a handful of microservices. That’s when it clicked: the brittle trust model we relied on wasn’t cutting it anymore.
As someone who’s been building secure APIs since .NET Framework days, I’ve wrestled with OAuth, JWT, API keys, you name it. But this incident forced me to dig deeper. We needed to move toward something stronger — Zero Trust, not just as a buzzword, but as a practical, enforceable architecture. That’s when I went all in on certificate-based mutual TLS (mTLS) for our .NET APIs.
Let me walk you through how we made the shift — not from a theoretical lens, but from the trenches of real-world, enterprise-grade .NET 8 APIs. This isn’t your typical “hello world” tutorial. This is about building bulletproof authentication, automating certificate rotation, and sleeping better at night.
Why I Gave Up on JWT (Mostly)
JWTs are great until they’re not. They’re stateless, compact, and easy to pass around. But they assume too much. They assume clocks are in sync. They assume you trust every service holding a private key. And most dangerously, they assume the bearer of the token is the rightful caller.
With Zero Trust, assumptions are the enemy. Mutual TLS changes the game by demanding proof from both client and server — every time, without shortcuts. You don’t just trust a token; you validate the client’s identity with a certificate chain issued from a trusted authority.
mTLS in .NET 8: No Longer a Nightmare
Back in .NET Core 2.x, doing mTLS felt like hacking your own plumbing. But .NET 8? Much smoother.
Here’s how we set it up:
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(httpsOptions =>
{
httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsOptions.CheckCertificateRevocation = true;
httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
{
// Implement proper chain validation here
return chain.ChainStatus.All(x => x.Status == X509ChainStatusFlags.NoError);
};
});
});
webBuilder.UseStartup();
});” 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″>
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(httpsOptions =>
{
httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsOptions.CheckCertificateRevocation = true;
httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
{
// Implement proper chain validation here
return chain.ChainStatus.All(x => x.Status == X509ChainStatusFlags.NoError);
};
});
});
webBuilder.UseStartup<Startup>();
});
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ConfigureHttpsDefaults(httpsOptions =>
{
httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
httpsOptions.CheckCertificateRevocation = true;
httpsOptions.ClientCertificateValidation = (cert, chain, errors) =>
{
// Implement proper chain validation here
return chain.ChainStatus.All(x => x.Status == X509ChainStatusFlags.NoError);
};
});
});
webBuilder.UseStartup<Startup>();
});
This code configures Kestrel to enforce client certificates on every HTTPS request. No certificate? No access. That’s Zero Trust.
Client Setup: Proving Identity With Every Call
We packaged our internal SDKs to handle certificate injection automatically. Here’s what a certificate-based HttpClientHandler looks like:
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(LoadClientCertificate());
var client = new HttpClient(handler)
{
BaseAddress = new Uri("https://api.ourcompany.internal")
};
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(LoadClientCertificate());
var client = new HttpClient(handler)
{
BaseAddress = new Uri("https://api.ourcompany.internal")
};
Where LoadClientCertificate() securely pulls the certificate from a local store or a secure secret manager like AWS Certificate Manager or Azure Key Vault—rotated monthly via pipeline automation.
Automatic Certificate Rotation: No More PagerDuty Alerts
Manual cert expiry is a nightmare waiting to happen. We integrated certificate rotation into our GitHub Actions pipeline. Here’s the flow:
- Request new cert from internal CA (via API).
- Store cert in Azure Key Vault with versioning.
- Trigger a redeployment with the new cert bound to the service identity.
- Notify downstream consumers (via internal registry or a shared config repo).
All this runs weekly. Certificates never hit disk. We even wrote a smoke test that verifies the new cert is working before the old one is deactivated.
Authorization Still Matters
mTLS proves the caller’s identity, but you still need to authorize their actions.
We layered policies on top of mTLS:
{
options.AddPolicy("CanReadInvoices", policy =>
{
policy.RequireAssertion(context =>
{
var cert = context.User.FindFirst("x509_thumbprint")?.Value;
return TrustedClientRegistry.AllowedThumbprintsFor("InvoiceRead").Contains(cert);
});
});
});” 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″>
services.AddAuthorization(options =>
{
options.AddPolicy("CanReadInvoices", policy =>
{
policy.RequireAssertion(context =>
{
var cert = context.User.FindFirst("x509_thumbprint")?.Value;
return TrustedClientRegistry.AllowedThumbprintsFor("InvoiceRead").Contains(cert);
});
});
});
services.AddAuthorization(options =>
{
options.AddPolicy("CanReadInvoices", policy =>
{
policy.RequireAssertion(context =>
{
var cert = context.User.FindFirst("x509_thumbprint")?.Value;
return TrustedClientRegistry.AllowedThumbprintsFor("InvoiceRead").Contains(cert);
});
});
});
Yes, we parse the certificate and map thumbprints to roles in a hardened registry — not perfect, but effective.
Real-World Lessons
- Monitoring is everything. You must log certificate subject, issuer, and thumbprint per request. We use AWS X-Ray and OpenTelemetry to trace certificate identity through the request chain.
- Revocation is non-negotiable. CRL or OCSP checks aren’t optional. We built our own OCSP stapling validator to bypass flaky platform defaults.
- Fallback is dangerous. Do not allow fallback to token auth in mTLS-secured zones. Zero Trust doesn’t coexist well with half-measures.
Was It Worth It?
Yes.
There’s a moment, about a month after rollout, when we detected a compromised service trying to spoof requests with an expired cert. Old us would’ve missed it — or worse, accepted it with a still-valid JWT. New us rejected it outright. No drama. No damage.
That’s the payoff of Zero Trust in action.
TL;DR (If You’ve Scrolled This Far, You’ve Earned It)
- JWTs are convenient but fall short in high-trust environments.
- mTLS enforces identity at the transport layer — no token tampering, no bearer abuse.
- .NET 8 finally makes certificate auth developer-friendly.
- Automate everything: cert issuance, storage, rotation, and verification.
- Build tooling to observe, trace, and authorize based on cert identity.
- Don’t fall into the trap of trusting your network — trust nothing by default.
This wasn’t just a technical shift. It was a cultural one. Our developers think about trust differently now. And honestly? That’s the best upgrade of all.
More Articles
Optimising .NET for High-Frequency Trading: Microseconds Matter
From profiling pain to performance breakthroughs — how we carved nanoseconds out of .NET
Zero-Allocation Patterns in Modern .NET Web APIs
How I Eliminated Hidden Allocations from a Real Production API. They Laughed When I Swapped ToList() — Until Our P95…
Building a Custom .NET Memory Profiler for Your Team
How I stopped guessing and started measuring
Using AWS DynamoDB with .NET for High-Performance NoSQL Applications
Learn how we scaled to 10M events/day using AWS DynamoDB with .NET — no joins, no SQL bottlenecks. See real-world…
Azure DevOps Is My Secret Weapon for Effortless .NET
Tired of brittle CI/CD pipelines in your .NET cloud apps? See how Azure DevOps transformed my deployment chaos into…
C# Programming🚀
Thank you for being a part of the C# community! Before you leave:
Follow us: LinkedIn | Dev.to
Visit our other platforms: GitHub
More content at C# Programming