Skip to content
Blog

← All articles

The Death of the Shared Secret: Private Key JWT Client Authentication (RFC 7523)

Why a static client_secret is the weakest link between services, and how private_key_jwt replaces it: the client signs a short-lived assertion with its own private key, and the server checks it with the public key. A tested client and token endpoint in Node.js, the RFC 10070 audience rule that fixed a 2025 vulnerability, key rotation, and ES256 vs. RS256 measured.

By 14 min read

When one service calls another's API, it usually starts by getting an access token from an authorization server, and it proves who it is with a client_secret: a password, stored in an environment variable and sent with every token request. Whoever has a copy of that string is the client, from anywhere, until someone notices and rotates it. Secrets leak in all the boring ways: a committed .env file, a debug log that prints request bodies, a CI variable shown in a build log, a backup of the authorization server's database.

Private key JWT client authentication removes the shared secret. The client keeps a private key that never leaves its machine, and for each token request it signs a short, single-use statement saying "I am this client". The authorization server checks the signature with the client's public key, which is not a secret at all. This article builds both sides in Node.js, follows the 2026 update to the rules (RFC 10070), and tests every way the check can be fooled. For the basics of signed tokens, see our JWT architecture guide.

The short answer#

The flaw in a shared secret#

The standard OAuth client credentials grant with client_secret_basic sends the secret in the Authorization header of every token request. TLS protects it in transit, but the secret still has to exist in three places: in the client's configuration, in every request (and every proxy, log, or debugging tool that sees one), and in the authorization server's database, which has to compare it. A copy from any of them works:

  • From anywhere. The secret proves nothing about where the request comes from.
  • Indefinitely. It stays valid until someone rotates it, and rotating means changing both sides at the same moment, so it rarely happens.
  • Quietly. A request with a stolen secret looks exactly like a request from the real client.

Hashing the secret on the server helps against database leaks, but not against the other two places. client_secret_jwt, which signs a JWT with an HMAC of the secret, keeps the secret off the wire but still needs the same secret on both sides. The real fix is to stop sharing.

How private_key_jwt works#

  1. Once, at registration, the client gives the authorization server its public key, or better, a jwks_uri: a URL where it publishes its public keys as a JSON Web Key Set.
  2. For each token request, the client creates a JWT with its own client_id as issuer and subject, the authorization server as audience, a unique ID, and an expiry a minute away, and signs it with its private key.
  3. It sends that JWT as client_assertion, with client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer.
  4. The authorization server looks up the client's public key, verifies the signature and the claims, remembers the ID so the same JWT can't be used again, and issues an access token.

The mechanism is RFC 7523, under the assertion framework of RFC 7521. OpenID Connect calls it private_key_jwt, the name most identity providers use in their settings.

The key pair#

keys.sh
# keys.sh: the client's key pair. The private key never leaves the client; the public key is all the
# authorization server ever needs.
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out client-key.pem   # for ES256
openssl pkey -in client-key.pem -pubout -out client-pub.pem
chmod 600 client-key.pem

ES256 (ECDSA on the P-256 curve) or RS256 (RSA) are the usual choices; both are supported everywhere. In our test, an ES256 assertion was 371 bytes and an RS256 one 627, because an RSA signature is 256 bytes against 64. Store the private key like any credential: file permissions at minimum, better a secrets manager, best a key management service or HSM that signs without ever exporting it.

The assertion#

FieldValueWhy
alg, kid (header)ES256 or RS256, and the key's IDWhich key in the client's JWKS to check it with
typ (header)client-authentication+jwtMarks its purpose, so it can't be mistaken for another kind of JWT (RFC 10070, recommended)
iss and subThe client_id, bothWho is authenticating
audThe authorization server's issuer identifierWho may accept it: one server, nobody else
jtiA unique IDLets the server refuse a second use
exp, iatNow plus about a minute, and nowLimits how long a copy is worth anything

The client#

client.mjs
// client.mjs: Server A, getting access tokens with a signed assertion instead of a client secret
// (private_key_jwt: RFC 7523, as updated by RFC 10070).
import { randomUUID } from "node:crypto";
import { SignJWT } from "jose";

export function createTokenClient({ clientId, issuer, tokenEndpoint, privateKey, kid, alg = "ES256" }) {
  let cached = null; // { token, expiresAt }

  const assertion = () =>
    new SignJWT({})
      .setProtectedHeader({ alg, kid, typ: "client-authentication+jwt" })
      .setIssuer(clientId)        // who is asking
      .setSubject(clientId)       // and about whom: the client itself
      .setAudience(issuer)        // the authorization server's issuer identifier, and nothing else
      .setJti(randomUUID())       // single use
      .setIssuedAt()
      .setExpirationTime("60s")   // useless a minute later
      .sign(privateKey);

  return async function getToken() {
    if (cached && cached.expiresAt - Date.now() > 30_000) return cached.token;
    const res = await fetch(tokenEndpoint, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "client_credentials",
        client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        client_assertion: await assertion(),
      }),
    });
    const body = await res.json();
    if (!res.ok) throw new Error(`token request failed: ${body.error}`);
    cached = { token: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
    return cached.token;
  };
}

A fresh assertion for every token request, and the access token cached until shortly before it expires, so the client signs about once per access-token lifetime, not once per API call. Our test captured the request on the wire: a form with the assertion and its type, and no secret of any kind.

The token endpoint#

token-endpoint.mjs
// token-endpoint.mjs: Server B's authorization server, authenticating clients by their signed assertions.
import { createRemoteJWKSet, jwtVerify, SignJWT } from "jose";

const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
const MAX_LIFETIME = 300; // seconds: refuse assertions that claim to be valid for longer

export function createTokenEndpoint({ issuer, clients, signingKey }) {
  // One cached key set per client, fetched from the jwks_uri it registered. An unknown kid triggers a refetch
  // (at most every 30 s), so a client can rotate keys by publishing a new one.
  const keySets = new Map(Object.entries(clients).map(([id, c]) =>
    [id, createRemoteJWKSet(new URL(c.jwks_uri), { cooldownDuration: 30_000 })]));
  const used = new Map(); // jti -> exp; in production, a table with a unique constraint or a Redis key

  const fail = (status = 401) => ({ status, body: { error: "invalid_client" } });

  async function authenticate(form) {
    if (form.client_assertion_type !== ASSERTION_TYPE || !form.client_assertion) return fail();
    let payload;
    try {
      const unverified = JSON.parse(Buffer.from(form.client_assertion.split(".")[1], "base64url"));
      const keySet = keySets.get(unverified.iss);
      if (!keySet) return fail();
      ({ payload } = await jwtVerify(form.client_assertion, keySet, {
        algorithms: ["ES256", "RS256"], // never "none", never HMAC with a public key
        issuer: unverified.iss,
        subject: unverified.iss,        // iss and sub must both be the client_id
        audience: issuer,
        requiredClaims: ["jti", "exp", "iat"],
        clockTolerance: 30,
      }));
    } catch {
      return fail();
    }
    // RFC 10070: our issuer identifier must be the sole audience value.
    if (Array.isArray(payload.aud) && payload.aud.length !== 1) return fail();
    if (payload.exp - payload.iat > MAX_LIFETIME) return fail();
    if (form.client_id && form.client_id !== payload.iss) return fail();
    // Single use: a copied assertion can't be replayed, even within its minute.
    const now = Math.floor(Date.now() / 1000);
    for (const [jti, exp] of used) if (exp < now - 60) used.delete(jti);
    if (used.has(payload.jti)) return fail();
    used.set(payload.jti, payload.exp);
    return { clientId: payload.iss };
  }

  return async function handle(form) {
    if (form.grant_type !== "client_credentials") return { status: 400, body: { error: "unsupported_grant_type" } };
    const client = await authenticate(form);
    if (client.status) return client;
    const accessToken = await new SignJWT({ client_id: client.clientId })
      .setProtectedHeader({ alg: "ES256", typ: "at+jwt" })
      .setIssuer(issuer)
      .setSubject(client.clientId)
      .setIssuedAt()
      .setExpirationTime("10m")
      .sign(signingKey);
    return { status: 200, body: { access_token: accessToken, token_type: "Bearer", expires_in: 600 } };
  };
}

Every line of the verification closes a specific hole:

  • The key comes from the client's registration, never from the JWT. Headers like jwk or jku that carry their own key or key URL are ignored.
  • An explicit algorithm list. Without it, a verifier could accept alg: none, or an HMAC signature computed with the public key as the secret.
  • iss and sub equal the client, and so does client_id if the request includes one.
  • A maximum lifetime. A client that signs assertions valid for a day would turn each one into a day-long password.
  • Single use. The jti is remembered until the assertion expires. Across several server instances, that set must be shared: a table with a unique constraint, or a Redis key set with an expiry.

The audience rule, and why it changed#

RFC 7523 let the audience be the authorization server's issuer identifier or its token endpoint URL, and many servers accepted a list. In February 2025, the OpenID Foundation disclosed an attack on that flexibility (CVE-2025-27370 and CVE-2025-27371): a malicious authorization server could get a client to put another server's identifier into the audience of assertions it sent to the malicious one, then replay them to the real server and act as the client there.

RFC 10070, published in 2026, closes it. For client authentication, the audience must be the authorization server's issuer identifier as its sole value; the token endpoint URL must not be used; and servers must reject anything else. Clients should also set typ to client-authentication+jwt, though servers shouldn't yet reject assertions without it. Our endpoint refused an audience of its own token endpoint URL, a list with a second audience, and another issuer, and accepted its issuer alone.

What we tested#

The client and the token endpoint ran as real HTTP servers, with the client's key made by the OpenSSL commands above (OpenSSL 3.5) and the public keys served at a jwks_uri. Seven checks passed, on Node.js 24 with jose 6.2:

  • The happy path: an access token for the OpenSSL key, a 60-second assertion with the expected header and claims, no secret in the request, and the token reused from cache on the next call.
  • Replay: the same assertion sent twice got 200, then 401 invalid_client.
  • Audience: the token endpoint URL, two audiences, or another issuer were refused.
  • Forgeries: an assertion signed by another key, one whose iss and sub differed, an unknown client, a missing jti, an expired assertion, and one valid for a day were all refused.
  • Algorithm attacks: alg: none and an HS256 signature made with the public key were refused.
  • Compatibility: an assertion without the typ header was still accepted, and a second client with an RSA key (RS256) worked alongside the ES256 one.
  • Rotation: a key the client published later was picked up without any change on the server.

Rotating keys without downtime#

With a jwks_uri, rotation needs no coordination. The client publishes the new public key next to the old one, waits until the authorization server can have fetched it, switches to signing with the new key, and later removes the old one. On the server, the key set is cached; a kid it doesn't know triggers a refetch, at most once per cooldown period (30 seconds in our code). Our test found the practical consequence: a key published just after the server fetched the set was refused until the cooldown passed, then accepted. So publish first, sign later.

Compare that with a shared secret, where the server must accept both the old and the new secret during the change, and someone has to put the new one into both systems.

Client authentication methods compared#

MethodWhat the client proves withShared secret?If the credential leaks
client_secret_basic / _postA password, sent each timeYesWorks from anywhere until rotated
client_secret_jwtA JWT signed with HMAC of the secretYes, on both sidesSame: anyone with the secret can sign
private_key_jwtA JWT signed with its private keyNoAssertions: a minute, once. The key: only if stolen from the client itself
Mutual TLS (RFC 8705)A client certificate in the TLS handshakeNoSame as a private key; can also bind tokens to the certificate
Workload identity federationA token from the platform it runs onNoNothing long-lived to leak

Mutual TLS gives similar protection and can also bind the access tokens to the client's certificate, but it needs TLS termination that passes client certificates through, which proxies and load balancers often don't. private_key_jwt works over any HTTPS connection. On a cloud platform, workload identity federation (the platform signs a token for the workload, and the other side trusts the platform) can remove even the private key.

What it doesn't solve#

  • A stolen private key. Whoever has it is the client. The difference from a secret is that it never travels, so it can only be stolen from the client's own machine or vault. Keeping it in a KMS or HSM that only signs closes even that.
  • Stolen access tokens. The access token the client receives is still a bearer token. Keep it short-lived, or bind it to the key with DPoP (RFC 9449) or mutual TLS.
  • A server that doesn't check carefully. Every refusal in our tests is a line of code in the endpoint. A library that verifies the signature but not the audience, lifetime, or replay leaves most of the protection on the table.

FAQ#

ES256 or RS256?

Either is secure. ES256 makes smaller assertions (371 bytes against 627 in our test) and signs about five times faster; RS256 verifies a little faster. Signing happens once per access token, so neither cost matters in practice. Use what your authorization server and key storage support best.

Can the client send the public key in the request?

No. The public key must come from the client's registration; a key that arrives with the JWT proves only that someone has a key pair. That's why the endpoint looks up the key by iss and ignores any key in the header.

Do I need the jti check if assertions expire in a minute?

Yes. A minute is plenty for an attacker who reads assertions from a log or a proxy. OpenID Connect makes jti required for private_key_jwt, and remembering it until the assertion expires costs very little.

How do I check what an assertion contains?

Paste it into our JWT decoder: it shows the header and claims and can verify the signature against the client's public key or JWKS.

Try it in your browser

  • JWT Decoder, Encoder & Editor: decode a client assertion to check its iss, sub, aud, jti and exp, and verify its signature with the client's public key or JWKS.
  • Hash Generator: see what an HMAC-based client_secret_jwt depends on: anyone with the shared secret can compute the same HMAC.