JSON Web Tokens come in two forms. Most are signed (JWS): the claims are readable by anyone, and a signature proves who issued them. Some are encrypted (JWE): the claims are hidden from everyone but the intended recipient. Choosing between them looks like a question of how much security you want, but it isn’t. They protect against different threats, and choosing the wrong one can either leak data or allow anyone to forge tokens.
This guide is about the decision: what each form protects, who holds which key, what it costs in size and speed, and which one fits common situations. For the internals, see our deep dives into JWT structure and verification and the mechanics of JWE. Every code example here was run before publishing, with the jose library on Node.js 24.
The short answer#
Two different promises#
| Question | JWS (signed) | JWE, shared key (dir, A256KW) | JWE, public key (RSA-OAEP, ECDH-ES) |
|---|---|---|---|
| Can anyone holding the token read it? | Yes | No | No |
| Is any change detected? | Yes | Yes | Yes |
| Does it prove who made it? | Yes: the private-key holder | Yes: someone with the shared key | No: anyone with the public key |
| Who can check it? | Anyone with the public key | Only the key holders | Only the recipient |
The last column is the one that surprises people. Public-key encryption protects the reader, not the writer. The recipient’s public key is public, so encryption with it says nothing about where the token came from. Our JWE article demonstrates forging a perfectly decryptable token with admin: true using nothing but a public key.
A signed token is a postcard#
A JWS is base64url-encoded JSON with a signature attached. Base64url is an encoding, not encryption, so anyone who gets hold of the token can read every claim, without any key:
// readable.mjs: a signed JWT hides nothing. No key is needed to read it.
import { SignJWT, generateKeyPair } from "jose";
const { privateKey } = await generateKeyPair("ES256");
const token = await new SignJWT({ sub: "42", email: "ada@example.com", plan: "enterprise" })
.setProtectedHeader({ alg: "ES256" })
.sign(privateKey);
// What a browser extension, a proxy log, or anyone holding the token can do:
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url"));
console.log(payload.email, payload.plan); // ada@example.com enterpriseTokens get around: browser storage and devtools, browser extensions, mobile app backups, reverse-proxy and load balancer logs, error trackers that capture request headers, analytics scripts, and sometimes URLs. Anything in a signed token should be something you’re comfortable with all of those seeing. Usually that means a user ID, scopes, and timestamps, and not email addresses, names, internal account numbers, or anything regulated.
Who holds which key#
With public keys, signing and encryption point in opposite directions:
JWS: one signer, many verifiers
The issuer keeps the private key and publishes the public key. Anyone can check a token; only the issuer can make one.
JWE: many senders, one reader
The recipient keeps the private key and publishes the public key. Anyone can make a token for it; only the recipient can read one.
That shapes the architecture. With JWS, one auth server can issue tokens for any number of APIs, and each API just downloads the issuer’s public keys (its JWKS). With JWE, the issuer needs each recipient’s public key, and a token encrypted for one API can’t be read by another. Tokens that several services must read are much easier to handle as JWS.
When to sign#
Sign when the main question a recipient asks is “did this really come from my auth server, unchanged?”:
- API access tokens. The JWT profile for OAuth 2.0 access tokens (RFC 9068) is a signed token with the subject, client, scopes, and audience.
- OpenID Connect ID tokens, which are always signed (and only optionally encrypted).
- Many verifiers. Microservices, edge functions and third parties can all verify with the published public keys, and none of them can mint tokens.
// sign.mjs: one issuer signs; any number of services verify with the public key alone.
import { SignJWT, jwtVerify, generateKeyPair, exportJWK, createLocalJWKSet } from "jose";
// The auth server: keeps the private key, publishes the public key (normally at /.well-known/jwks.json).
const { publicKey, privateKey } = await generateKeyPair("ES256");
const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid: "2026-11", alg: "ES256", use: "sig" }] };
const token = await new SignJWT({ scope: "orders:read" })
.setProtectedHeader({ alg: "ES256", kid: "2026-11" })
.setSubject("42")
.setIssuer("https://auth.example.com")
.setAudience("https://api.example.com")
.setExpirationTime("15m")
.sign(privateKey);
// Any API: needs only the published JWKS. It can check tokens but can never create one.
const keys = createLocalJWKSet(jwks); // createRemoteJWKSet(url) in production
const { payload } = await jwtVerify(token, keys, {
algorithms: ["ES256"],
issuer: "https://auth.example.com",
audience: "https://api.example.com",
});
console.log(payload.sub, payload.scope); // 42 orders:readThe verifier pins the algorithm, issuer and audience. That matters as much as the signature itself. Without it, a token issued for one API could be replayed against another, and the classic algorithm-confusion attacks described in our JWT guide become possible.
When to encrypt#
Encrypt when the token carries data that the parties in between shouldn’t see:
- Stateless session cookies. The server stores session data in the cookie itself, encrypted with a key only it has. The browser carries it but can’t read or change it.
- Tokens through untrusted middle parties: a mobile app or a partner system that passes a token to your API but shouldn’t learn what’s in it.
- Personal data in tokens. If an ID token must carry an address or a national ID, OpenID Connect lets the client request it be encrypted.
For the session case, use a shared key with dir and A256GCM. Only the server has the key, so a token that decrypts was made by the server: you get secrecy and authenticity in one step, with the smallest JWE there is.
// session.mjs: an encrypted session cookie. One server, one shared key: "dir" + A256GCM.
import { EncryptJWT, jwtDecrypt } from "jose";
// Keys by ID, so you can rotate: encrypt with the newest, still decrypt with older ones.
const keys = {
"2026-10": crypto.getRandomValues(new Uint8Array(32)),
"2026-11": crypto.getRandomValues(new Uint8Array(32)),
};
const current = "2026-11";
export async function seal(session) {
return new EncryptJWT(session)
.setProtectedHeader({ alg: "dir", enc: "A256GCM", kid: current })
.setIssuedAt()
.setExpirationTime("8h")
.encrypt(keys[current]);
}
export async function open(cookie) {
const keyFor = (header) => {
if (!keys[header.kid]) throw new Error("unknown key");
return keys[header.kid];
};
const { payload } = await jwtDecrypt(cookie, keyFor, {
keyManagementAlgorithms: ["dir"],
contentEncryptionAlgorithms: ["A256GCM"],
});
return payload;
}
const cookie = await seal({ userId: 42, cart: ["sku-123"], role: "customer" });
console.log(cookie.split(".").length, cookie.length < 4096); // 5 true: fits in one cookie
console.log((await open(cookie)).cart); // [ 'sku-123' ]
// Neither readable nor changeable by the browser: any edit fails decryption.
const edited = cookie.slice(0, -2) + (cookie.at(-2) === "A" ? "B" : "A") + cookie.at(-1);
await open(edited).catch((e) => console.log(e.code)); // ERR_JWE_DECRYPTION_FAILEDThe key ID in the header lets you rotate keys: new cookies use the newest key, and cookies issued with the previous key keep working until they expire. Our test also checked that a cookie naming an unknown key is rejected.
When to do both#
Combine them when a token needs secrecy, and its recipient can’t share a symmetric key with the issuer: the issuer signs with its private key, then encrypts the signed token with the recipient’s public key. This is a nested JWT, marked with cty: "JWT":
// nested.mjs: sign, then encrypt. The recipient learns who issued the token, and nobody else can read it.
import { SignJWT, CompactEncrypt, compactDecrypt, jwtVerify, generateKeyPair } from "jose";
const issuer = await generateKeyPair("ES256"); // auth server: signs
const api = await generateKeyPair("ECDH-ES", { crv: "X25519" }); // one API: decrypts
async function issue(claims) {
const jws = await new SignJWT(claims).setProtectedHeader({ alg: "ES256" }).setIssuer("https://auth.example.com").setExpirationTime("15m").sign(issuer.privateKey);
return new CompactEncrypt(new TextEncoder().encode(jws))
.setProtectedHeader({ alg: "ECDH-ES", enc: "A256GCM", cty: "JWT" }) // cty says: the payload is a JWT
.encrypt(api.publicKey);
}
async function accept(token) {
const { plaintext, protectedHeader } = await compactDecrypt(token, api.privateKey, {
keyManagementAlgorithms: ["ECDH-ES"],
contentEncryptionAlgorithms: ["A256GCM"],
});
if (protectedHeader.cty !== "JWT") throw new Error("expected a signed JWT inside");
const { payload } = await jwtVerify(new TextDecoder().decode(plaintext), issuer.publicKey, {
algorithms: ["ES256"],
issuer: "https://auth.example.com",
});
return payload;
}
const token = await issue({ sub: "42", email: "ada@example.com" });
console.log(token.split(".").length); // 5: from the outside, it's a JWE
console.log((await accept(token)).email); // ada@example.comSign first, then encrypt. The signature is then hidden along with the claims, the recipient checks the issuer’s signature after decrypting, and it’s the order RFC 7519 and libraries expect. The cost is size and two operations per token, measured below.
When to use neither#
JWTs are popular because they’re self-contained: a service can check one without calling anybody. That’s also their weakness. A valid token stays valid until it expires, even after the user logs out or is disabled, unless you add a revocation list, which brings back the server-side lookup JWTs were meant to avoid. If your server keeps session state anyway, an opaque token is simpler and leaks nothing:
// opaque.mjs: the third option. A random reference token reveals nothing and can be revoked instantly.
import { randomBytes } from "node:crypto";
const sessions = new Map(); // in production: Redis or a database table, keyed by the token
function login(userId) {
const token = randomBytes(32).toString("base64url"); // 256 random bits, meaningless outside your server
sessions.set(token, { userId, expires: Date.now() + 8 * 3600_000 });
return token;
}
const lookup = (token) => {
const s = sessions.get(token);
return s && s.expires > Date.now() ? s : null;
};
const token = login(42);
console.log(token.length, lookup(token).userId); // 43 42
sessions.delete(token); // logout or revocation takes effect immediately
console.log(lookup(token)); // nullThe two approaches also combine well. Many systems give the browser an opaque token and have the API gateway exchange it for a short-lived JWT for internal services, a pattern sometimes called the phantom token. The outside world sees nothing, and internal services still get self-contained tokens.
Size and speed#
We measured each option with the same seven claims (172 bytes of JSON: subject, email, scope, issuer, audience, and two timestamps), using jose 6.2.13 on Node.js 24, in two runs:
| Token | Size (characters) | Created per second | Checked per second |
|---|---|---|---|
| JWS HS256 | 295 | 13–16k | 18k |
| JWS ES256 | 338 | 12–13k | 10k |
| JWS EdDSA (Ed25519) | 338 | 14k | 9k |
| JWS RS256 (2048-bit) | 594 | 2.3k | 15k |
JWE dir + A256GCM | 311 | 13k | 16k |
| JWE A256KW + A256GCM | 369 | 7k | 8k |
| JWE ECDH-ES (X25519) + A256GCM | 430 | 3.6k | 5.2k |
| JWE RSA-OAEP-256 (2048-bit) + A256GCM | 665 | 6.8k | 2.0k |
Nested: ES256 inside dir | 548 | 6.5k | 5.7k |
| Nested: ES256 inside RSA-OAEP-256 | 902 | 4.3k | 1.6k |
- Speed rarely decides. Each option handled thousands of tokens per second on a single core. Only RSA’s private-key operations (RS256 signing, RSA-OAEP decryption) stand out as slow.
- Size can. A cookie is limited to about 4 KB, and servers and proxies limit total header size (nginx defaults to 8 KB per header line, Node.js to 16 KB for all headers). A nested RSA token is three times the size of an HS256 one, before you add any more claims.
- A
dirJWE is barely bigger than a signed token: 311 characters against 295 for HS256, and smaller than ES256.
Library support#
JWS is supported everywhere; JWE isn’t. Several of the most popular JWT libraries only handle signed tokens, and they don’t always fail clearly when given a JWE:
// wrong-library.mjs: what a JWS-only library does with a JWE (npm install jsonwebtoken jose).
import jwt from "jsonwebtoken";
import { EncryptJWT } from "jose";
const key = crypto.getRandomValues(new Uint8Array(32));
const jwe = await new EncryptJWT({ sub: "42" }).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).encrypt(key);
console.log(jwt.decode(jwe)); // null: no error, just nothing
try {
jwt.verify(jwe, Buffer.from(key));
} catch (e) {
console.log(e.message); // jwt malformed
}jwt.decode() returning null instead of throwing is the dangerous part: code that checks the result carelessly can treat a token it couldn’t read as an anonymous one. Python’s PyJWT 2.10 fails with a confusing message about an invalid payload string. Check JWE support before you choose it:
| Library | Language | JWS | JWE |
|---|---|---|---|
| jose | JavaScript (all runtimes) | Yes | Yes |
| jsonwebtoken | Node.js | Yes | No |
| PyJWT | Python | Yes | No |
| jwcrypto, joserfc | Python | Yes | Yes |
| golang-jwt | Go | Yes | No |
| go-jose | Go | Yes | Yes |
| Nimbus JOSE + JWT | Java | Yes | Yes |
| Microsoft.IdentityModel.JsonWebTokens | .NET | Yes | Yes |
jose, jsonwebtoken, PyJWT and jwcrypto were tested for this article and our JWE article; the others are from their documentation.
A decision guide#
| Situation | Use |
|---|---|
| Access token for your APIs, no sensitive claims | JWS (ES256 or EdDSA) |
| ID token for a client application | JWS; nested JWE if it carries personal data |
| Session data stored in a cookie by one server | JWE, dir + A256GCM |
| Token passed through a party that mustn’t read it, issued with public keys | Nested: JWS inside JWE |
| Token read by many services that each need the claims | JWS, with only non-sensitive claims |
| You need instant logout or revocation | Opaque token, or very short-lived JWTs |
| Server keeps session state anyway | Opaque token |
Common mistakes#
- Putting secrets in a JWS because it “looks encrypted”. It’s Base64.
- Trusting a public-key JWE as proof of origin. Anyone can create one. Sign first, or use a shared key.
- Encrypting everything by default. JWE adds size, cost, and library constraints. If the claims aren’t sensitive, a JWS is simpler for everyone who has to debug, verify, or support it.
- Not pinning algorithms. For JWS, pin
alg; for JWE, pin bothalgandenc. Never let the token choose. - Logging tokens. A signed token in a log is readable claims plus a credential someone can replay until it expires. Log a token ID (
jti) instead. - Long-lived JWTs without revocation. Keep access tokens short (minutes), and use refresh tokens or opaque sessions for long-lived access.
FAQ#
Is a JWE “more secure” than a JWS?
No, it’s differently secure. A JWS guarantees origin and integrity but not secrecy; a public-key JWE guarantees secrecy and integrity but not origin. A dir JWE, or a nested token, gives all three.
Can I just encrypt the sensitive claims inside a JWS?
You can, but you end up inventing your own format, with your own choices of cipher, nonce handling, and key identification, all of which JWE already standardizes. If part of the token needs encryption, encrypt the token.
Should HS256 tokens be used across services?
Only if every service is trusted to issue tokens, since the same shared secret both signs and verifies. For many services, use an asymmetric algorithm, so verifiers can’t mint tokens.
How do I see what’s inside a token?
For a JWS, decode it: our JWT decoder shows the header and claims and can verify the signature. For a JWE, you need the key; our JWE tool shows its five parts and decrypts it using a private key, a shared key, or a password.
Get the code
- jwt-dpop-sample on GitHub: signed (JWS) access tokens and encrypted (JWE) refresh tokens side by side in ASP.NET Core, with a token inspector that shows what each one reveals.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode a signed token to see exactly what it reveals, and verify its signature with a secret, PEM key or JWKS.
- JWE Decoder, Encoder & Editor: create and decrypt encrypted tokens, including dir, ECDH-ES and RSA-OAEP, to compare their size and structure.