C# / .NET Compendium PLEN
.NET / C# / Security

Securing a Web API: JWT, OAuth 2.0, OIDC, SSO and certificates

Securing a Web API is several independent layers. You have to distinguish authentication (who you are), authorization (what you're allowed to do) and protection of the channel (TLS, certificates) and of the application itself (validation, limits). The cryptography basics this rests on are in the topic Cryptography: symmetric and asymmetric encryption, hashing, TLS.

1. Authentication: how the API knows who is asking

Mechanism How it works When
Basic Auth Authorization: Basic base64(user:pass) on every request only over HTTPS, simple internal tools; avoid in new systems
API Key a fixed key in a header (X-Api-Key) machine-to-machine integrations, public APIs with limits; identifies the client, not the user
JWT Bearer the client sends a signed token Authorization: Bearer <jwt>, the API verifies the signature, exp, iss, aud without looking into the database SPAs, mobile apps, microservices
OAuth 2.0 / OIDC tokens are issued by an authorization server (see below) login through an external provider, SSO, delegated access
Cookie a session in a cookie (HttpOnly, Secure, SameSite) MVC/Razor and Blazor Server on a single domain; less common in a pure API
mTLS (a client certificate) both sides present a certificate service-to-service communication, banking, IoT

2. JWT, OAuth 2.0, OpenID Connect and SSO are not the same thing

  • JWT is a token format: a header, a payload with claims and a signature (xxxxx.yyyyy.zzzzz, the parts in Base64URL). On its own it is not a login protocol.
  • OAuth 2.0 is a delegated authorization protocol: "application X may read my data in service Y on my behalf". It issues an access token (often a JWT) and a refresh token. It is not a login protocol.
  • OpenID Connect (OIDC) is an identity layer on top of OAuth 2.0: it adds an ID token saying who the user is. It is OIDC that implements "sign in with Google/Microsoft".
  • SSO (Single Sign-On) is a goal: to log in once and have access to many applications. It is achieved through OIDC or SAML (older, popular in corporations) with a central identity provider (Entra ID, Keycloak, Auth0, Okta, Duende IdentityServer).

In practice the Identity Provider issues tokens (OIDC/OAuth 2.0), and the API (the resource server) only validates them. The API shouldn't handle passwords itself if it can be avoided.

OAuth 2.0 flows (grant types)

  • Authorization Code + PKCE - the standard for SPAs, mobile and web applications with a user. The browser receives a one-time code, exchanges it for a token, and PKCE protects against its interception.
  • Client Credentials - service-to-service communication, with no user (the client authenticates with a secret or a certificate).
  • Implicit and Password are obsolete - don't use them in new systems.

3. Authorization: what is allowed

In ASP.NET Core usually several levels:

  • Roles - [Authorize(Roles = "Admin")],
  • Claims and policies - [Authorize(Policy = "CanEditOrders")], i.e. more flexible rules,
  • Scopes in the token - e.g. orders.read, orders.write,
  • Resource authorization - whether this user may edit this specific record (IAuthorizationService or an ownership check in the handler). Omitting it is the most common BOLA/IDOR hole: you change /orders/5 to /orders/6 in the address and see somebody else's data.

The difference in response codes: 401 Unauthorized = a missing or bad token (we don't know who you are), 403 Forbidden = we know who you are, but you're not allowed.

4. Certificates in securing an API

4.1 The server certificate (TLS / HTTPS) - the foundation

An X.509 certificate binds a public key to an identity (a domain) and is signed by a trusted CA. The client checks the chain of trust, validity, name match (SAN) and revocation (CRL/OCSP). This gives three things: encryption, server authentication and integrity. Details of key agreement: Cryptography.

  • A public API uses a certificate from a public CA (e.g. Let's Encrypt, renewed automatically every 90 days).
  • TLS is often terminated at a reverse proxy / load balancer (nginx, OpenLiteSpeed, Azure Front Door, Cloudflare), and traffic goes to Kestrel locally.
  • Enable HSTS (app.UseHsts()) and the redirect from HTTP (app.UseHttpsRedirection()).
  • Locally: dotnet dev-certs https --trust (a development certificate, not for production).

4.2 mTLS: authentication with a client certificate

In mutual TLS the client also presents a certificate, and the server checks whether a trusted CA issued it. The private key is never sent, so it can't be intercepted or guessed.

  • Makes sense: service-to-service communication (often automatically in a service mesh: Istio, Linkerd), B2B integrations, banking (PSD2 requires qualified certificates), IoT devices.
  • Doesn't make sense: a public SPA with end users - installing and rotating certificates on every device is too burdensome.

Kestrel requiring a client certificate (the Microsoft.AspNetCore.Authentication.Certificate package):

builder.WebHost.ConfigureKestrel(k =>
{
    k.ConfigureHttpsDefaults(https =>
    {
        https.ClientCertificateMode = ClientCertificateMode.RequireCertificate;
    });
});

builder.Services
    .AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
    .AddCertificate(options =>
    {
        options.AllowedCertificateTypes = CertificateTypes.Chained; // only certs chained to a trusted CA
        options.RevocationMode = X509RevocationMode.Online;         // check CRL/OCSP

        options.Events = new CertificateAuthenticationEvents
        {
            OnCertificateValidated = ctx =>
            {
                // extra check: allow only known thumbprints
                var allowed = new[] { "A1B2C3...THUMBPRINT" };
                if (!allowed.Contains(ctx.ClientCertificate.Thumbprint, StringComparer.OrdinalIgnoreCase))
                {
                    ctx.Fail("Unknown client certificate");
                    return Task.CompletedTask;
                }

                var claims = new[] { new Claim(ClaimTypes.Name, ctx.ClientCertificate.Subject) };
                ctx.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ctx.Scheme.Name));
                ctx.Success();
                return Task.CompletedTask;
            }
        };
    });

A C# client (HttpClient with a certificate):

var cert = new X509Certificate2("client.pfx", "pfx-password");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(cert);

using var client = new HttpClient(handler) { BaseAddress = new Uri("https://api.example.com") };
var response = await client.GetAsync("/api/orders");

A trap - the reverse proxy: if TLS is terminated at the proxy, Kestrel won't see the client certificate. The proxy has to forward it in a header (e.g. X-ARR-ClientCert), and the application read it through AddCertificateForwarding and app.UseCertificateForwarding(). Trust such a header only from your own proxy, because otherwise anyone can forge it.

4.3 Certificates and keys in JWT tokens

  • The JWT signature: the identity provider signs the token with a private key (RS256/ES256), and the API checks the signature with a public key fetched from the JWKS endpoint (/.well-known/jwks.json). The API knows no secret, and keys can be rotated. A symmetric signature (HS256) requires both sides to know the secret, so with many services it is risky.
  • Certificate-bound tokens (RFC 8705): the token contains a cnf claim with the client certificate's thumbprint, so a stolen token is useless without the private key (used in banking, FAPI).
  • Client authentication in OAuth 2.0: the client proves itself to the authorization server with a certificate (tls_client_auth) or a signed JWT (private_key_jwt) instead of a shared secret.

4.4 Certificate pinning

The client (usually a mobile app) knows in advance the expected certificate or public key of the server and rejects any other, even one issued by a trusted CA. This protects against a forged certificate and MITM if a CA is compromised. The downside: the risk of "killing" the application when the certificate is replaced, so you pin rather the public key or an intermediate certificate and have a contingency plan. In .NET this is done through ServerCertificateCustomValidationCallback.

4.5 The certificate life cycle - the most common source of outages

  • Expiry: a certificate that wasn't renewed can take production down. Automate renewals (ACME/certbot, Azure Key Vault) and monitor the dates.
  • Rotation: plan the replacement without downtime (for a while both the old and the new certificate are valid).
  • The private key: not in the repository or in appsettings.json. Use Key Vault, an HSM or the system's certificate store, and protect the .pfx file with a password.
  • Revocation: after a key leak the certificate has to be revoked (CRL/OCSP). A shorter certificate lifetime reduces the damage.
  • Your own CA for microservices inside the company: step-ca, HashiCorp Vault PKI, Active Directory Certificate Services. Remember to distribute the root certificate.

5. Other layers of protection

  • HTTPS and HSTS - without this, tokens and passwords travel in plain text.
  • Input validation - DTOs instead of entities (against over-posting), FluentValidation, parameterised queries (EF) against SQL injection.
  • CORS restricted to known origins (this is browser protection, not protection of the API as such).
  • Rate limiting / throttling against brute force and abuse - see Rate limiting.
  • Anti-CSRF - only when you use cookies. With a token in the Authorization header CSRF doesn't apply.
  • Passwords - a salted hash (PBKDF2/bcrypt/Argon2), never encryption or a raw hash.
  • Secrets in Key Vault, environment variables or User Secrets.
  • Errors - no stack traces for the client (ProblemDetails), logging and auditing of security events.
  • An API Gateway / WAF (Azure API Management, Kong, YARP) as a central point for authentication, limits and filtering.

6. JWT: the most common pitfalls

  • The token is signed, not encrypted - don't put secrets in it, anyone can read the payload.
  • Revocation is hard (the token is self-contained), so use a short access token lifetime (5-15 min) and a refresh token (rotated, stored securely), optionally a list of revoked tokens.
  • Always validate the signature, exp, iss, aud, and set the allowed algorithms explicitly (the alg: none attack and confusing RS256 with HS256).
  • Where to keep the token in a SPA: localStorage is vulnerable to XSS, and an HttpOnly cookie to CSRF (you need SameSite and CSRF protection). The BFF (Backend for Frontend) pattern keeps tokens on the server side.

7. A working example - SecureApiDemo

A minimal API (.NET 8, the Microsoft.AspNetCore.Authentication.JwtBearer package). It shows: issuing a token, JWT validation, a scope-based policy, a role, and resource authorization (a user sees only their own order). The token is issued here by the API itself purely for demo purposes - in production the identity provider does it, and the API only validates.

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// DEMO ONLY: in production the key lives in a secret store (Key Vault) and tokens are issued
// by an identity provider (Entra ID, Keycloak, Duende...). Here the API issues tokens itself.
const string Issuer = "https://demo.local";
const string Audience = "orders-api";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("demo-key-change-me-at-least-32-bytes-long!!"));

// ---- AUTHENTICATION: who is calling? ----
builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.MapInboundClaims = false; // keep claim names as in the token ("sub", "role", "scope")
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, ValidIssuer = Issuer,
            ValidateAudience = true, ValidAudience = Audience,
            ValidateLifetime = true, ClockSkew = TimeSpan.FromSeconds(30),
            ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey,
            ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }, // never accept "alg: none"
            NameClaimType = "name", RoleClaimType = "role"
        };
    });

// ---- AUTHORIZATION: what is the caller allowed to do? ----
builder.Services.AddAuthorization(o =>
{
    o.AddPolicy("CanReadOrders", p => p.RequireAssertion(ctx => HasScope(ctx.User, "orders.read")));
    o.AddPolicy("AdminOnly", p => p.RequireRole("admin"));
});

var app = builder.Build();

app.UseAuthentication(); // 1st: build the user from the token
app.UseAuthorization();  // 2nd: check policies

// demo users and data
var users = new Dictionary<string, (string Password, string Id, string Role)>
{
    ["alice"] = ("alice123", "1", "user"),
    ["bob"] = ("bob123", "2", "user"),
    ["admin"] = ("admin123", "99", "admin")
};
var orders = new List<Order>
{
    new(1, "1", "Laptop"), new(2, "1", "Mouse"), new(3, "2", "Keyboard")
};

// anonymous: issue a token (in real life: login + password check + rate limiting)
app.MapPost("/login", (LoginRequest request) =>
{
    if (!users.TryGetValue(request.Username, out var u) || u.Password != request.Password)
        return Results.Unauthorized();

    var claims = new[]
    {
        new Claim("sub", u.Id),
        new Claim("name", request.Username),
        new Claim("role", u.Role),
        new Claim("scope", "orders.read orders.write")
    };
    var token = new JwtSecurityToken(
        issuer: Issuer, audience: Audience, claims: claims,
        expires: DateTime.UtcNow.AddMinutes(10),           // short-lived access token
        signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));

    return Results.Ok(new { access_token = new JwtSecurityTokenHandler().WriteToken(token) });
});

app.MapGet("/api/public", () => "anyone can see this");

// policy based on scope: the token needs "orders.read"
app.MapGet("/api/orders", (ClaimsPrincipal user) =>
{
    var isAdmin = user.IsInRole("admin");
    var userId = user.FindFirstValue("sub");
    return orders.Where(o => isAdmin || o.OwnerId == userId);
}).RequireAuthorization("CanReadOrders");

// resource-based authorization: the user may read only HIS OWN order (protection against IDOR/BOLA)
app.MapGet("/api/orders/{id:int}", (int id, ClaimsPrincipal user) =>
{
    var order = orders.FirstOrDefault(o => o.Id == id);
    if (order is null) return Results.NotFound();

    var isOwner = order.OwnerId == user.FindFirstValue("sub");
    if (!isOwner && !user.IsInRole("admin")) return Results.Forbid(); // 403: authenticated, but not allowed
    return Results.Ok(order);
}).RequireAuthorization(); // 401 without a valid token

// role-based
app.MapDelete("/api/orders/{id:int}", (int id) =>
{
    var removed = orders.RemoveAll(o => o.Id == id);
    return removed > 0 ? Results.NoContent() : Results.NotFound();
}).RequireAuthorization("AdminOnly");

app.Run();

static bool HasScope(ClaimsPrincipal user, string scope) =>
    (user.FindFirstValue("scope") ?? string.Empty).Split(' ').Contains(scope);

record LoginRequest(string Username, string Password);
record Order(int Id, string OwnerId, string Item);

The project (SecureApiDemo.csproj):

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
  </ItemGroup>

</Project>

Try it (dotnet run, then curl or a requests.http file):

# 1) without a token -> 401
curl -i http://localhost:5000/api/orders

# 2) log in as alice and copy the access_token
curl -X POST http://localhost:5000/login -H "Content-Type: application/json" \
     -d '{"username":"alice","password":"alice123"}'

# 3) alice's orders -> 200
curl http://localhost:5000/api/orders -H "Authorization: Bearer <access_token>"

# 4) someone else's order (id 3 belongs to bob) -> 403
curl -i http://localhost:5000/api/orders/3 -H "Authorization: Bearer <access_token>"

# 5) delete without the admin role -> 403 (log in as admin/admin123 to get 204)
curl -i -X DELETE http://localhost:5000/api/orders/1 -H "Authorization: Bearer <access_token>"

What this example shows

  • Middleware order: UseAuthentication() builds the user from the token, and only then does UseAuthorization() check the policies.
  • 401 vs 403: no token gives 401, and a lack of permissions with a valid token gives 403.
  • A scope policy (CanReadOrders) and a role (AdminOnly).
  • Resource authorization: [Authorize] alone isn't enough, because it doesn't check whose order it is.
  • An explicit list of algorithms (ValidAlgorithms) and validation of iss, aud, exp.

8. What to choose in typical situations

Scenario Recommendation
Your own SPA or mobile app plus an API OIDC with Authorization Code + PKCE, a JWT access token, the API as a resource server
Many applications in a company, one login (SSO) a central IdP (Entra ID, Keycloak) with OIDC or SAML
A service calls a service OAuth 2.0 Client Credentials or mTLS
A public API for partners An API Key plus rate limiting, and OAuth 2.0 when accessing user data
B2B integration, banking mTLS plus tokens, often qualified certificates
A simple internal MVC on one domain cookie authentication

They are usually combined in layers: TLS protects the channel, the client certificate the machine's identity, and the user token what a specific person may do.

See also

Interview questions

  • How does authentication differ from authorization? Authentication establishes who you are, authorization what you're allowed to do (401 vs 403).
  • JWT vs OAuth 2.0 vs OIDC vs SSO? JWT is a token format, OAuth 2.0 is a delegated authorization protocol, OIDC adds identity (login) to it, and SSO is a goal achieved through OIDC or SAML.
  • How does an API verify a JWT? It checks the signature with the public key from the issuer's JWKS (or a shared key with HS256) and exp, iss, aud, without looking into the database.
  • How do you revoke a JWT? A short lifetime plus a refresh token with rotation, optionally a list of revoked tokens.
  • Which OAuth flow for a SPA? Authorization Code with PKCE (not Implicit).
  • How does TLS differ from mTLS? In TLS only the server presents a certificate, in mTLS both sides do.
  • Why isn't mTLS suitable for a public SPA? Managing certificates on end users' devices is impractical.
  • What is IDOR/BOLA? Access to other people's resources by swapping an identifier, when the API checks only that you're logged in, not the owner. Defence: resource authorization.
  • Where to store the token in a SPA? Most safely on the server side (a BFF with an HttpOnly cookie), while localStorage is vulnerable to XSS.
  • What to do when a certificate expires? Clients will reject the connection, which is why we automate renewals and monitor expiry dates.
Buy me a coffee