Trading a license for short-lived tokens
A signed license is the right object to prove what a customer bought and the wrong object to hand a downstream service on every request. It is large. It carries the whole purchase - seats, editions, renewal terms - when the service checking it only wants to know one thing.
And if every service verifies it by asking the license server, that server is suddenly on the hot path of every request in your system, which is precisely where a licensing component should never be.
The instinct is to cache the answer. But a cache of "is this license valid" is a revocation problem in disguise: the moment you cache, you have to decide how stale an answer you will tolerate, and you are back to distributing freshness.
There is a cleaner shape, and the identity world already settled on it. The real question RFC 8693 describes OAuth token exchange: a client presents one token and receives another, narrower one, minted for a specific purpose. Licensing has the same shape. The client presents its long-lived signed license once to a token-exchange endpoint and gets back a short-lived capability token - a tiny signed object carrying only the scopes one service needs, an audience naming that service, and an exp a few minutes out.
Each service verifies that small token offline with a pinned public key. The license server mints and then disappears from the request path. The question this post answers is how to build that mint and that offline verify so the crypto is actually correct - and what you give up to keep the license server off the hot path.
The license is presented once and projected down to a short-lived, narrowly-scoped capability token. Each service verifies that token offline - signature, audience, expiry - and never calls the license server, which is why revocation latency equals the token lifetime.
A real ES256 token
The capability token is a compact JWS: base64url(header).base64url(payload).base64url(signature). The signature algorithm is ES256 - ECDSA over the NIST P-256 curve with SHA-256 - because the .NET base class library ships it. (Ed25519 would be a fine choice too, but there is no Ed25519 in System.Security.Cryptography; you would reach for NSec or BouncyCastle. ECDSA keeps every line below copy-paste real against the BCL.)
The one subtlety that trips people up: JWS does not use a DER-encoded ECDSA signature. It uses the raw fixed-width r‖s concatenation, which the BCL calls DSASignatureFormat.IeeeP1363FixedFieldConcatenation. Get that wrong and your tokens will not verify against any standard JWT library.
Two tiny helpers handle the base64url dialect (no padding, URL-safe alphabet):
static class B64Url {
public static string Encode(ReadOnlySpan<byte> b) =>
Convert.ToBase64String(b).TrimEnd('=').Replace('+', '-').Replace('/', '_');
public static byte[] Decode(string s) {
var t = s.Replace('-', '+').Replace('_', '/');
t = (t.Length % 4) switch { 2 => t + "==", 3 => t + "=", _ => t };
return Convert.FromBase64String(t);
}
}
Minting: present the license, get a capability
The exchange endpoint is the only component that holds the private key. It verifies the presented license, derives the scopes for the one service the caller is headed to, and signs a token that expires in minutes.
public sealed class TokenMint(ECDsa signingKey, string keyId, string issuer) {
public string Exchange(License license, string audience, TimeSpan lifetime) {
var now = DateTimeOffset.UtcNow;
var header = new Dictionary<string, object> {
["alg"] = "ES256",
["typ"] = "at+jwt",
["kid"] = keyId, // tells the verifier which public key
};
var payload = new Dictionary<string, object> {
["iss"] = issuer,
["aud"] = audience, // the ONE service this token is for
["iat"] = now.ToUnixTimeSeconds(),
["exp"] = now.Add(lifetime).ToUnixTimeSeconds(),
["jti"] = Guid.NewGuid().ToString("n"),
["scope"] = string.Join(' ', ScopesFor(license, audience)),
};
var signingInput = $"{B64Url.Encode(JsonSerializer.SerializeToUtf8Bytes(header))}." +
$"{B64Url.Encode(JsonSerializer.SerializeToUtf8Bytes(payload))}";
// ES256 = ECDSA/P-256/SHA-256 with the JWS r‖s signature layout.
byte[] sig = signingKey.SignData(
Encoding.ASCII.GetBytes(signingInput),
HashAlgorithmName.SHA256,
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
return $"{signingInput}.{B64Url.Encode(sig)}";
}
// Project the long-lived entitlements down to what THIS service may do.
// The keys are generic, vendor-chosen examples - not any product's internals.
static IEnumerable<string> ScopesFor(License license, string audience) =>
license.Entitlements.Where(e => e.AppliesTo(audience)).Select(e => e.Scope);
// e.g. "export.pdf", "seats:5"
}
The license itself is verified first, exactly once, with its own long-lived key - the same canonical-bytes signature check you already run. Everything the mint emits after that is derived: the token says nothing the license did not already grant.
Verifying: offline, one signature, no call home
Each downstream service holds only the public half of the signing key, pinned, plus its own name. Verification is four checks and zero network.
public static bool TryVerify(string token, ECDsa publicKey, string expectedAudience, TimeProvider clock, out Capability cap) {
cap = default!;
var p = token.Split('.');
if (p.Length != 3) return false;
// 1. Signature over the EXACT bytes that were signed - header.payload.
var signingInput = Encoding.ASCII.GetBytes($"{p[0]}.{p[1]}");
var signature = B64Url.Decode(p[2]);
if (!publicKey.VerifyData(signingInput, signature, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation))
return false;
// 2. Only parse claims once the signature holds.
using var doc = JsonDocument.Parse(B64Url.Decode(p[1]));
var root = doc.RootElement;
// 3. Audience must name THIS service - not some other one.
if (root.GetProperty("aud").GetString() != expectedAudience) return false;
// 4. Freshness, with a small symmetric clock-skew leeway.
var now = clock.GetUtcNow();
var exp = DateTimeOffset.FromUnixTimeSeconds(root.GetProperty("exp").GetInt64());
var iat = DateTimeOffset.FromUnixTimeSeconds(root.GetProperty("iat").GetInt64());
var skew = TimeSpan.FromSeconds(30);
if (now > exp + skew || now < iat - skew) return false;
cap = new Capability(
Scopes: (root.GetProperty("scope").GetString() ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries),
Expires: exp);
return true;
}
Signature before claims is not a stylistic choice - reading aud or scope out of an unverified token means acting on attacker-controlled JSON. VerifyData with the matching DSASignatureFormat returns false for any token not signed by the private key, so nothing past step 1 runs on a forged token.
The public key is loaded once at startup, for example from a pinned SubjectPublicKeyInfo:
var publicKey = ECDsa.Create();
publicKey.ImportSubjectPublicKeyInfo(pinnedSpki, out _);
A service then enforces a capability by asking the parsed token, never the network:
if (!TryVerify(bearer, publicKey, "report-service", TimeProvider.System, out var cap) ||
!cap.Scopes.Contains("export.pdf"))
return Results.Forbid();
Caveats, and the one that defines the design
Revocation latency equals the token lifetime. This is the price, stated plainly. Because the services never call the license server, a revoked license keeps working at every service until the last capability token it minted expires. A five-minute lifetime means a cancelled or downgraded license can keep acting for up to five minutes. You cannot have both zero per-request round-trips and instant revocation - the lifetime is the dial between them. Choose it for the worst revocation you genuinely need to act on: seconds if a charge-back must bite immediately, a few minutes if human-scale latency is fine and you want fewer mints.
Clock skew cuts both ways. Freshness is a time comparison, so a verifier whose clock is wrong will accept an expired token or reject a valid one. The symmetric 30-second leeway above absorbs normal drift; it does not save a machine whose clock is wildly wrong, which is the same exposure every expiry-based check carries.
The public key has to be distributed and rotated. Verifiers pin the public key, so rotating the signing key means shipping a new public key and keeping the previous one accepted for an overlap window at least as long as the token lifetime, so tokens already in flight still verify. The kid header is what lets a verifier hold several public keys at once and pick the right one.
A still-valid token can be replayed. Within its short lifetime, a captured token works wherever its aud points. That is exactly why aud names one service and scope is as narrow as the service needs: a leaked token reaches only the one audience it was minted for and only the capabilities already granted there. Short lifetime, narrow audience, narrow scope - those three are the whole containment story, and jti lets a service that wants belt-and-braces keep a short replay-cache keyed on it.
Takeaway
A long-lived license answers "what did this customer buy?" - a slow-changing, high-value fact that belongs under a key you guard closely. A downstream service asks a smaller, faster question: "may this request export a PDF in the next few minutes?" Token exchange lets you answer the second without dragging the first onto the hot path. Present the license once, mint a tiny ES256 capability token scoped to one audience, and let every service verify it offline against a pinned public key. The only thing you trade away is instant revocation - and because the token lifetime is a number you set deliberately, that trade is yours to make rather than the network's to impose.
Keyright ships the signing and verification primitives, including the ECDSA token helpers above; the docs cover wiring the exchange endpoint and pinning verifier keys. The free Community Edition verifies tokens; minting and scope derivation are enforcement features of the paid editions.
Comments
No comments yet. Start the discussion.