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.

JavascriptAuth Jwt

Code

javascriptsnippet
23 lines
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

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.