In The Death of the Shared Secret, a client proved who it was with a signed JWT, the client assertion, instead of a client_secret, and a library built that JWT in a few lines. This article opens the box. We build the same assertion with no JWT library at all, in Node.js, a shell script with OpenSSL, Python, Go, and Java, so you can see every byte that gets signed.
That's more than an exercise. When a token endpoint answers invalid_client and nothing else, knowing exactly what the assertion must look like is how you find the problem. And sometimes there's no library: a CI step with only a shell, or a platform where adding a dependency takes a security review. Every version below was run, and each one's output was accepted by the token endpoint from the previous article.
The short answer#
The anatomy of an assertion#
A client assertion is a JWT in the JWS compact serialization (RFC 7515): three parts separated by dots.
eyJhbGciOiJFUzI1NiIsImtpZCI6Ik83a2Z4… base64url(header)
.
eyJpc3MiOiJvcmRlcnMiLCJzdWIiOiJvcmRl… base64url(claims)
.
2m9tBy0bHhCwN4kRgo6x3Ak1_pGEZuKfn9Hr… base64url(signature)
The signature covers the first two parts and the dot between them.The first two parts are readable by anyone: base64url is an encoding, not encryption. Only the third proves anything, and it proves that whoever holds the private key produced exactly the bytes before the second dot.
Step 1: the header#
| Field | Value | Why |
|---|---|---|
alg | ES256, RS256 or PS256 | The signature algorithm. The server must also have its own list of allowed values and never trust this one alone. |
kid | The key's ID in your JWKS | Tells the server which of your published keys to use, which matters during a key rotation. |
typ | client-authentication+jwt | Recommended by RFC 10070 so an assertion can't be mistaken for another kind of JWT. |
Leave out jwk, jku, x5u, and x5c. They carry a key or a key URL inside the token, and a server must get your key from your registration, never from the request.
Step 2: the claims#
| Claim | Value | Notes |
|---|---|---|
iss, sub | Your client_id | Both, and the same. RFC 7523 requires them. |
aud | The issuer identifier, e.g. https://as.example.com | A single string. Not the token endpoint URL (RFC 10070). |
exp | iat + 60 | Required. Seconds since 1970 (a NumericDate), not milliseconds. |
iat | Now, in seconds | Lets the server measure the lifetime and refuse long ones. |
jti | A random UUID or 128 random bits | Optional in RFC 7523, required by OpenID Connect; the server uses it to refuse replays. |
Step 3: base64url and the signing input#
Serialize the header and the claims as JSON, and encode each with base64url: standard base64 with + replaced by -, / by _, and the trailing = removed (RFC 7515, section 2). Join them with a dot. That string is the JWS signing input, and its ASCII bytes are exactly what you sign.
Two consequences catch people. First, the server never re-creates the JSON: it checks the signature over the base64url text it received, so key order and whitespace don't matter, as long as you sign the same bytes you send. Go's encoding/json sorts map keys, so its claims start with aud, and it's still valid. Second, you sign the encoded text, not the JSON. Signing {"alg":…}.{"iss":…} produces a perfectly good signature over the wrong bytes.
Step 4: the signature#
- ES256: ECDSA on the P-256 curve with SHA-256. The signature is two 256-bit numbers,
rands, written as 32 bytes each, big-endian, one after the other: 64 bytes (RFC 7518, section 3.4). - RS256: RSASSA-PKCS1-v1_5 with SHA-256. The signature is as long as the key: 256 bytes for 2048-bit RSA.
- PS256: RSASSA-PSS with SHA-256. Same size as RS256, with a random salt. FAPI 2.0 allows PS256, ES256 and EdDSA, but not RS256.
The DER trap#
Most crypto libraries return an ECDSA signature in DER, the format used by X.509 certificates and TLS: an ASN.1 SEQUENCE of two INTEGERs. DER drops leading zero bytes from each integer and adds a 00 when the top bit is set, so the length varies. Over 100,000 P-256 signatures, we counted 70, 71, and 72 bytes about 25%, 50%, and 25% of the time, 69 bytes about 0.2%, and once or twice per run 67 or 68.
JWS has no room for any of that. The signature must be r and s as exactly 32 bytes each. Send DER and the server reads the wrong bytes as r and s, so the check fails: jose answered ERR_JWS_SIGNATURE_VERIFICATION_FAILED and the token endpoint 401. What each platform gives you:
| Platform | Default ECDSA output | How to get r || s |
|---|---|---|
Node.js crypto.sign | DER | { key, dsaEncoding: "ieee-p1363" } |
Web Crypto (crypto.subtle.sign) | r || s | Nothing to do |
OpenSSL dgst -sign | DER | Parse with asn1parse and pad each integer |
Python cryptography | DER | decode_dss_signature, then to_bytes(32, "big") |
Go ecdsa.Sign / SignASN1 | Two integers / DER | FillBytes into 32-byte halves |
Java SHA256withECDSA | DER | Use SHA256withECDSAinP1363Format |
The padding is where hand-written converters break. A converter that just strips a leading 00 works for about 99.2% of signatures and fails on the rest, when r or s happens to be shorter than 32 bytes (a chance of 1 in 256 for each). That's about one token request in 128: a bug that looks like a flaky network.
Node.js, by hand#
Only node:crypto. The three numbered comments are the whole blueprint; everything else is plumbing.
// assertion.mjs: a private_key_jwt client assertion built by hand with node:crypto, no JWT library.
// node assertion.mjs client-key.pem orders https://as.example.com [ES256|RS256]
// node assertion.mjs --kid client-key.pem
import { createHash, createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto";
import { readFileSync } from "node:fs";
// base64url: base64 with - and _ instead of + and /, and no = padding (RFC 7515, section 2).
const b64url = (data) => Buffer.from(data).toString("base64url");
// kid: the RFC 7638 thumbprint. Only the required members, in alphabetical order, no whitespace, then SHA-256.
export function thumbprint(publicKey) {
const jwk = publicKey.export({ format: "jwk" });
const members = jwk.kty === "EC"
? { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }
: { e: jwk.e, kty: jwk.kty, n: jwk.n };
return b64url(createHash("sha256").update(JSON.stringify(members)).digest());
}
export function createAssertion({ privateKey, clientId, audience, kid, alg = "ES256" }) {
const now = Math.floor(Date.now() / 1000); // seconds, not milliseconds
const header = { alg, kid, typ: "client-authentication+jwt" };
const payload = { iss: clientId, sub: clientId, aud: audience, jti: randomUUID(), iat: now, exp: now + 60 };
// 1. The signing input: base64url(header) "." base64url(payload). These ASCII bytes are what gets signed.
const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
// 2. The signature. ES256 must be the raw 64 bytes r || s ("ieee-p1363"); sign() returns DER by default.
const signature = alg === "ES256"
? sign("sha256", Buffer.from(signingInput), { key: privateKey, dsaEncoding: "ieee-p1363" })
: sign("sha256", Buffer.from(signingInput), privateKey); // RS256: RSASSA-PKCS1-v1_5 with SHA-256
// 3. The compact serialization: three base64url parts joined by dots.
return `${signingInput}.${b64url(signature)}`;
}
if (import.meta.main && process.argv[2] === "--kid") { // import.meta.main: run directly, not imported (Node 24)
console.log(thumbprint(createPublicKey(readFileSync(process.argv[3]))));
} else if (import.meta.main) {
const [keyFile, clientId, audience, alg] = process.argv.slice(2);
const privateKey = createPrivateKey(readFileSync(keyFile));
const kid = thumbprint(createPublicKey(privateKey));
console.log(createAssertion({ privateKey, clientId, audience, kid, alg }));
}The kid: a key thumbprint#
A kid can be any string you publish with the key, but a good default is the key's RFC 7638 thumbprint: the SHA-256 of a canonical JSON of the public key. Canonical means only the required members (crv, kty, x, y for EC; e, kty, n for RSA), in alphabetical order, with no whitespace. It's derived from the key, so it never collides with another key and never needs to be stored. Our thumbprint() gave the same value as jose's calculateJwkThumbprint for both key types.
OpenSSL in a shell script#
The hard part is the DER conversion: openssl asn1parse lists the two integers in hex, and awk pads each to 64 hex digits or cuts a leading 00. We ran it 1,000 times to make sure the rare short integers come out right: in two runs, 6 and 11 of the 2,000 integers started with a zero byte, and all 1,000 assertions verified both times.
#!/bin/sh
# assertion.sh: the same ES256 assertion with OpenSSL and a POSIX shell (no JWT library).
# KID=... sh assertion.sh client-key.pem orders https://as.example.com
# The values go into the JSON unescaped, so keep them to plain characters (or build the JSON with jq).
set -eu
key=$1 client=$2 aud=$3
b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }
now=$(date +%s)
header=$(printf '{"alg":"ES256","kid":"%s","typ":"client-authentication+jwt"}' "$KID" | b64url)
payload=$(printf '{"iss":"%s","sub":"%s","aud":"%s","jti":"%s","iat":%d,"exp":%d}' \
"$client" "$client" "$aud" "$(openssl rand -hex 16)" "$now" $((now + 60)) | b64url)
input="$header.$payload"
# openssl dgst signs ECDSA as DER: SEQUENCE { INTEGER r, INTEGER s }, usually 70 to 72 bytes. A JWS needs r and s as
# two 32-byte numbers, so take both integers out, pad each to 64 hex digits (or drop a leading 00), and join them.
signature=$(printf '%s' "$input" | openssl dgst -sha256 -sign "$key" | openssl asn1parse -inform DER |
awk -F: '/INTEGER/ { h = $NF; while (length(h) < 64) h = "0" h; printf "%s", substr(h, length(h) - 63) }' |
xxd -r -p | b64url)
echo "$input.$signature"Python#
With the cryptography package, which signs in DER; decode_dss_signature gives back the two integers. Note separators=(",", ":"): it's not required, but without it the JSON has spaces and the assertion is a few bytes longer.
# assertion.py: the same ES256 assertion with the cryptography package (no JWT library).
# KID=... python assertion.py client-key.pem orders https://as.example.com
import base64, json, os, sys, time, uuid
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def encode(obj) -> str:
return b64url(json.dumps(obj, separators=(",", ":")).encode()) # compact JSON, no spaces
def create_assertion(private_key, client_id: str, audience: str, kid: str) -> str:
now = int(time.time())
header = {"alg": "ES256", "kid": kid, "typ": "client-authentication+jwt"}
payload = {"iss": client_id, "sub": client_id, "aud": audience,
"jti": str(uuid.uuid4()), "iat": now, "exp": now + 60}
signing_input = f"{encode(header)}.{encode(payload)}"
der = private_key.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256())) # DER, like OpenSSL
r, s = decode_dss_signature(der)
return f"{signing_input}.{b64url(r.to_bytes(32, 'big') + s.to_bytes(32, 'big'))}"
if __name__ == "__main__":
with open(sys.argv[1], "rb") as f:
key = serialization.load_pem_private_key(f.read(), password=None)
print(create_assertion(key, sys.argv[2], sys.argv[3], os.environ["KID"]))Go#
Only the standard library. ecdsa.Sign returns r and s as big integers, and FillBytes writes each into exactly 32 bytes, zero-padded on the left, which is exactly what JWS wants.
// assertion.go: the same ES256 assertion with Go's standard library (no JWT library).
// KID=... go run assertion.go client-key.pem orders https://as.example.com
package main
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"os"
"time"
)
func b64url(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } // Raw = no padding
func createAssertion(key *ecdsa.PrivateKey, clientID, audience, kid string) (string, error) {
now := time.Now().Unix()
jti := make([]byte, 16)
rand.Read(jti)
header, _ := json.Marshal(map[string]string{"alg": "ES256", "kid": kid, "typ": "client-authentication+jwt"})
payload, _ := json.Marshal(map[string]any{
"iss": clientID, "sub": clientID, "aud": audience,
"jti": fmt.Sprintf("%x", jti), "iat": now, "exp": now + 60,
})
input := b64url(header) + "." + b64url(payload)
digest := sha256.Sum256([]byte(input))
r, s, err := ecdsa.Sign(rand.Reader, key, digest[:]) // two big integers, not DER
if err != nil {
return "", err
}
sig := make([]byte, 64)
r.FillBytes(sig[:32]) // left-padded with zeros to exactly 32 bytes each
s.FillBytes(sig[32:])
return input + "." + b64url(sig), nil
}
func main() {
pemBytes, err := os.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
block, _ := pem.Decode(pemBytes)
parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
assertion, err := createAssertion(parsed.(*ecdsa.PrivateKey), os.Args[2], os.Args[3], os.Getenv("KID"))
if err != nil {
panic(err)
}
fmt.Println(assertion)
}Java#
The JDK alone, run as a single-file program. The one line that matters is the algorithm name: SHA256withECDSAinP1363Format returns r || s, plain SHA256withECDSA returns DER.
// Assertion.java: the same ES256 assertion with the JDK alone (no JWT library).
// KID=... java Assertion.java client-key.pem orders https://as.example.com
// The values go into the JSON unescaped, so keep them to plain characters (or use a JSON library).
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.UUID;
public class Assertion {
static String b64url(byte[] data) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(data);
}
static String createAssertion(PrivateKey key, String clientId, String audience, String kid) throws Exception {
long now = System.currentTimeMillis() / 1000; // seconds
String header = "{\"alg\":\"ES256\",\"kid\":\"%s\",\"typ\":\"client-authentication+jwt\"}".formatted(kid);
String payload = "{\"iss\":\"%s\",\"sub\":\"%s\",\"aud\":\"%s\",\"jti\":\"%s\",\"iat\":%d,\"exp\":%d}"
.formatted(clientId, clientId, audience, UUID.randomUUID(), now, now + 60);
String input = b64url(header.getBytes("UTF-8")) + "." + b64url(payload.getBytes("UTF-8"));
// "SHA256withECDSA" would return DER; the P1363 variant returns the raw r || s that JWS needs.
Signature signer = Signature.getInstance("SHA256withECDSAinP1363Format");
signer.initSign(key);
signer.update(input.getBytes("US-ASCII"));
return input + "." + b64url(signer.sign());
}
public static void main(String[] args) throws Exception {
String pem = Files.readString(Path.of(args[0])).replaceAll("-----[A-Z ]+-----|\\s", "");
PrivateKey key = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem)));
System.out.println(createAssertion(key, args[1], args[2], System.getenv("KID")));
}
}What we tested#
One P-256 key and one 2048-bit RSA key made with OpenSSL 3.5, then Node.js 24.22, Python 3.14 with cryptography 50.0, Go 1.25, and Java 25, each in its own container. Their assertions were checked with jose 6.2 and with the token endpoint from the previous article, which fetched the public keys from a jwks_uri. Seven checks passed, in two runs:
- The kid: our hand-made thumbprint matched jose's for the EC and the RSA key.
- Every language: the Node.js (ES256 and RS256), shell, Python, Go, and Java assertions had the expected header and claims, a 64-byte (or 256-byte RSA) signature, no padding, a unique
jti, and times in seconds. All verified, and the token endpoint answered 200 to each. - The shell script, 1,000 times: every assertion verified, including the ones with short integers.
- DER: a DER signature was refused.
- Encoding mistakes: see the next section.
- Milliseconds: refused by the endpoint, but not by jose alone.
- Randomness: two ES256 signatures of the same input were different and both verified; two RS256 signatures were identical. Web Crypto returned a 64-byte
r || sthat verified as is.
Mistakes that end in invalid_client#
| Mistake | jose 6.2 alone | Token endpoint |
|---|---|---|
| DER signature instead of r || s | Rejects | 401 |
Standard base64 (+ and /) | Rejects | 401 |
| Claims re-serialized (pretty-printed) after signing | Rejects | 401 |
| Signed the JSON instead of the base64url text | Rejects | 401 |
iat/exp in milliseconds | Accepts | 401 (lifetime too long) |
= padding left on | Accepts | 200 |
The last two rows are the interesting ones. Milliseconds produce an exp more than 56,000 years away, which a plain signature check is happy with; only a lifetime limit catches it, one more reason to have one. Padding was tolerated by jose, so a client that leaves it on can work for years and then fail against a stricter server. Don't count on it.
Should you build it by hand?#
For production code, usually not. A maintained library (jose for JavaScript, PyJWT or Authlib for Python, golang-jwt for Go, Nimbus JOSE+JWT for Java) handles the encoding and the signature format for you and has been tested against far more servers than your code will be. Building it by hand is worth it when:
- you're debugging an
invalid_clientand need to know what correct looks like; - a shell script or a locked-down environment can't take a dependency;
- you sign with a key in a KMS or HSM, which returns a bare signature (often DER) and leaves the JWT to you.
The last case is the common one in practice: AWS KMS and Google Cloud KMS return ECDSA signatures in DER, so the conversion in this article is exactly the piece you need. (A PKCS#11 token is the exception: its ECDSA mechanism already returns r || s.)
FAQ#
Why is my ES256 signature 70 or 72 bytes?
It's DER. Convert it to r || s, 32 bytes each, as shown above; a JWS ES256 signature is always exactly 64 bytes.
Does the order of the JSON keys matter?
No. The server verifies the bytes you sent and then parses them. What matters is that you sign the same bytes you send, so never re-serialize after signing.
Can I reuse an assertion for several token requests?
No. Each has a unique jti, and a server that follows OpenID Connect refuses the second use. Make a new one per request; signing takes well under a millisecond.
How do I check an assertion I built?
Paste it into our JWT decoder with your public key: it shows the header and claims and tells you whether the signature verifies. A 64-byte ES256 signature is 86 base64url characters; if yours is longer, it's DER.
Try it in your browser
- JWT Decoder, Encoder & Editor: paste an assertion you built by hand to see its header and claims and verify the signature with your public key.
- Base64 Encoder / Decoder: decode each part of an assertion, and see the difference between base64 and base64url.