notes.dt.in.th

jose (JWT) cookbook

This note contains various snippets for doing JWT stuff using the jose library.

Verifying JWT

import { jwtVerify } from 'jose'
import { createPublicKey } from 'crypto'

const publicKey = createPublicKey(publicKeyStr)
const result = await jwtVerify(authToken, async () => publicKey)

Generating JWT

import { SignJWT } from 'jose'
import { createPrivateKey } from 'crypto'

const privateKey = createPrivateKey(privateKeyStr)
const payload = {
  /* ... */
}
const kid = '...'
const expiresIn = 86400

const token = await new SignJWT(payload)
  .setProtectedHeader({ alg: 'RS256', kid })
  .setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn)
  .sign(privateKey)

HS256

For HS256, use createSecretKey instead of createPrivateKey or createPublicKey:

import { createSecretKey } from 'crypto'
const secretKey = createSecretKey('my random string', 'utf-8')

Generating keypairs

See Generating keypairs for JWT