Protecting JWT signing keys with an HSM or cloud KMS
Every token your identity provider issues is only as trustworthy as the private key that signs it. If that key leaks—committed to a repo, read out of an environment variable by a compromised dependency, or copied off a backup—an attacker can mint a token for any user, any tenant, any scope, and your services will accept all of them as genuine. Rotating after the fact helps, but every token signed before you noticed is valid until it expires. The durable fix is to make sure the key material never exists anywhere your application code can read it.
Signing as a service, not a secret
A Hardware Security Module (HSM) or a cloud KMS inverts the usual relationship. Instead of your app holding the key and computing a signature, your app sends the bytes it wants signed to the module, and the module returns a signature. The private key is generated inside the hardware and is marked non-exportable: there is no API, legitimate or otherwise, that returns the raw key. A breach of your application servers leaks the ability to request signatures while the HSM credential is valid—bad, but revocable—not the key itself, which would be catastrophic and permanent.
This maps cleanly onto JWTs. A JWT is three parts: a header, a payload, and a signature over base64url(header) + "." + base64url(payload). You build the first two parts in your app, hand the signing input to the KMS, and splice the returned signature on.
import { KMSClient, SignCommand } from "@aws-sdk/client-kms";
const kms = new KMSClient({});
const b64url = (b: Buffer) =>
b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
async function signJwt(payload: object, keyId: string) {
const header = { alg: "RS256", typ: "JWT", kid: keyId };
const signingInput =
b64url(Buffer.from(JSON.stringify(header))) + "." +
b64url(Buffer.from(JSON.stringify(payload)));
const { Signature } = await kms.send(new SignCommand({
KeyId: keyId,
Message: Buffer.from(signingInput),
MessageType: "RAW",
SigningAlgorithm: "RSASSA_PKCS1_V1_5_SHA_256",
}));
return signingInput + "." + b64url(Buffer.from(Signature!));
}The app never sees the private key. The IAM policy on that KMS key grants exactly one permission—kms:Sign—to exactly one service role. Verification, by contrast, needs only the public key, which you publish openly at your JWKS endpoint. Nothing about verification touches the HSM, so it stays fast and free of a network round trip.
Why kid matters here: put the KMS key id (or an alias for it) in the JWT header's kid field. Verifiers use it to select the right public key from your JWKS, and it makes rotation a matter of signing new tokens under a new kid while the old public key stays published until the last token signed with it expires.
The latency question
A KMS sign call is a network request—typically single-digit to low-tens of milliseconds. If you sign one token per login, that is invisible. If you re-sign on every API request, it is a disaster. The architecture that works is short-lived and cached at the right layer: sign access tokens with a few-minutes lifetime at login and on refresh, and never per request. Verification happens locally with the cached public key, so the hot path never calls the HSM at all.
When per-signature calls are too expensive
Some systems issue enormous volumes of short-lived tokens—think a token minted per outbound service call. Paying an HSM round trip for each is both slow and costly (cloud KMS bills per sign operation). The usual compromise is an intermediate signing key: the HSM signs a medium-lived signing certificate, and your app uses that cert to sign the high-volume tokens in-process. You've narrowed the blast radius—a leak now exposes a key that expires in hours and is itself attested by the HSM—without paying per token. It is a tradeoff, not a free lunch: document it.
Choosing a key type
RSA-2048 with RS256 is the safe interoperable default; nearly every JWT library verifies it. If you control both ends and want smaller signatures and faster operations, an EC key (P-256 with ES256) is excellent and widely supported. Avoid anything that requires the verifier to also hold a secret—HS256 and its siblings use a symmetric key, which defeats the entire point: now the secret needed to verify is also the secret needed to forge, and it has to live on every service.
The alg confusion attack: a verifier that trusts the token's own alg header can be tricked. The classic exploit sends alg: none, or swaps RS256 for HS256 and signs with your public key as the HMAC secret. Always pin the expected algorithm in the verifier's configuration and reject anything else—never let the token tell you how to check it.
Rotation and disaster recovery
Non-exportable keys change how recovery works. You cannot restore a signing key from a backup, because there was never a copy to back up. That is the point—but it means your continuity plan is key rotation, not key restore. Keep at least two keys live: a current signing key and a previous one still published for verification. Script the rotation so promoting a new key is a routine, rehearsed operation rather than a 3 a.m. scramble. And keep a break-glass procedure: if the active key's HSM region is unreachable, you want a pre-provisioned standby key in another region ready to take over signing immediately.
The real win is that key compromise stops being an existential event. When signing lives in hardware you control and verification needs only public material, a stolen server is a contained incident you rotate out of—not a reason to invalidate every session you've ever issued. Running your own identity layer means you decide where that key lives; Bastionary supports external signing through PKCS#11 and cloud KMS so the private key stays in your hardware, not in its process.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.