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

snippet
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);