Jose ES256 JWT Sign and Verify With Key Pair
Sign and verify JWTs with the jose library using an ECDSA P-256 key pair, protected headers, and explicit audience and expiry validation.
Code
import { SignJWT, jwtVerify, generateKeyPair, ExportJWK } from 'jose';
const { publicKey, privateKey } = await generateKeyPair('ES256', {
extractable: true,
});
const secretClaims = { sub: 'user-42', role: 'editor' };
const token = await new SignJWT(secretClaims)
.setProtectedHeader({ alg: 'ES256', typ: 'JWT' })
.setIssuer('https://auth.example.com')
.setAudience('api://orders')
.setExpirationTime('15m')
.setIssuedAt()
.sign(privateKey);
const { payload, protectedHeader } = await jwtVerify(token, publicKey, {
issuer: 'https://auth.example.com',
audience: 'api://orders',
clockTolerance: 5,
});
console.log(protectedHeader.alg, payload.role, payload.exp);What the code does
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Everything borrowed from jose is visible in one line: SignJWT, jwtVerify, generateKeyPair, ExportJWK.
The file’s state is a handful of top-level bindings: secretClaims, token.
The top-level object literal pins sub, role as plain values — no derivation, no imports behind them.
Points of care
- Dependency check:
jose— not built-in, must be present in the project.
Statements that matter
const { payload, protectedHeader } = await jwtVerify(token, publicKey, {
issuer: 'https://auth.example.com',
audience: 'api://orders',
clockTolerance: 5,
});
const { publicKey, privateKey } = await generateKeyPair('ES256', {
extractable: true,
});
const token = await new SignJWT(secretClaims)
.setProtectedHeader({ alg: 'ES256', typ: 'JWT' })
.setIssuer('https://auth.example.com')
.setAudience('api://orders')
.setExpirationTime('15m')
.setIssuedAt()
.sign(privateKey);
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Do I need to install anything before running this?
- Yes: `jose` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.