Validate claims
Accept a token only when it comes from the issuer you trust, is meant for your API, and is inside its time window; write those time claims when you sign.
Claims are the statements a JWT payload makes: who issued it (iss), who it's about (sub), who it's for (aud), when it was issued (iat), and the window it's valid in (nbf to exp). A valid signature only proves who wrote them. Whether you believe them for this request is up to the checks below. Concepts covers the vocabulary.
#Before you start
verifyanddecryptcheckexpandnbfon every JSON payload, with no option needed. The identity claims are only checked when you ask: withoutaudience, a token meant for another API passes.- Claims are checked after the signature or decryption succeeds, so a forged token fails as a forgery first.
- Time claims are in seconds since 1970 (a NumericDate), not milliseconds:
Math.floor(Date.now() / 1000), neverDate.now(). - Claim options need a JSON payload whose claims are checked.
issuer,audience,subject,maxTokenAgeorrequiredClaimswithpayload: "string"or"bytes", or withvalidateClaims: false, throwsERR_INVALID_OPTIONinstead of letting a token through unchecked.clockToleranceandcurrentDateare accepted either way.
#Check a token's claims
Name what your API expects, once, and pass it on every call:
import { sign, verify } from "unjwt/jws";
// The issuer's key pair, loaded once at start-up: see /jwk/generate.
export interface AccessClaims {
sub: string;
scope: string;
iat: number;
exp: number;
}
/** Issue an access token for one user, valid for 15 minutes. */
export function issueAccessToken(userId: string, scope: string) {
return sign(
{ iss: "https://auth.example.com", aud: "https://api.example.com", sub: userId, scope },
privateKey,
{
expiresIn: "15m",
protectedHeader: { typ: "at+jwt" },
},
);
}
/** The claims of a token this API accepts, or a `JWTError` saying why not. */
export async function readAccessToken(token: string) {
const { payload } = await verify<AccessClaims>(token, publicKey, {
algorithms: ["ES256"],
typ: "at+jwt",
issuer: "https://auth.example.com",
audience: "https://api.example.com",
requiredClaims: ["sub", "scope", "exp"],
maxTokenAge: "1h",
clockTolerance: 30,
});
return payload;
}issuer:issmust equal it, or one entry of a list. Setting it makesissrequired.audience:aud, a string or a list, must contain it, or one entry of a list. Setting it makesaudrequired.typ: the protected header'stypmust match, compared as a media type (RFC 7515 §4.1.9): case doesn't matter andapplication/is optional, so"at+jwt"matchesapplication/AT+JWT. It keeps an ID token or a refresh token signed by the same key from passing as an access token. A token withouttypfails.signwritestyp: "JWT"on an object payload unless you set one.requiredClaims: names that must be present, whatever their value.expis in the list so a token without an expiry never passes.maxTokenAge:iatmust be no older than this, even whenexpis later. It makesiatrequired, and aniatin the future fails.clockTolerance: seconds, or a duration, of clock difference allowed onexp,nbfandiat. Keep it small: it widens every token's window by that much.subject(not shown):submust equal it. Setting it makessubrequired.
Every option you set is checked, never skipped for being empty: issuer: "" or audience: [""] throws ERR_INVALID_OPTION. An empty list, audience: [], is a check no token passes.
#Write the time claims when you sign
sign and encrypt write iat, exp and nbf for you from relative or absolute times:
/** Valid from the start of the event until it ends, whenever the ticket was issued. */
export function issueEventTicket(holder: string, event: { startsAt: Date; endsAt: Date }) {
return sign({ sub: holder, aud: "https://tickets.example.com" }, privateKey, {
notBeforeAt: event.startsAt,
expiresAt: event.endsAt,
});
}- Relative or absolute:
expiresInandnotBeforeIncount from now;expiresAtandnotBeforeAttake aDate. Give one of each pair, not both. iatcomes along: anyexpornbfoption also writesiat.issuedAt: truewritesiaton its own, andissuedAt: someDatewrites that instant.currentDate: the clock everything counts from, the current time by default. Set it in tests.- Your claims win: a claim already in the payload is kept as you wrote it, so
{ exp }in the payload beatsexpiresIn. - Object payloads only: a string or bytes payload has no claims to write into, so a time option with one throws
ERR_INVALID_OPTION.
#Write a duration
Every option that takes a span of time (expiresIn, notBeforeIn, maxTokenAge, clockTolerance, and a session's maxAge) takes a number of seconds or a whole number followed by a unit:
| Unit | Seconds | Spellings |
|---|---|---|
| second | 1 | s, second, seconds, or no unit |
| minute | 60 | m, minute, minutes |
| hour | 3600 | h, hour, hours |
| day | 86400 | D, day, days |
| week | 604800 | W, week, weeks |
| month | 2592000 | M, month, months (30 days) |
| year | 31536000 | Y, year, years (365 days) |
Units are case-sensitive: m is minutes, M is months, and d is not a unit, so "7d" throws ERR_INVALID_OPTION; write "7D" or "7days". No space between number and unit, no fractions: "1.5h" throws, "90m" works. Durations are positive, except notBeforeIn, where 0 sets nbf to now, and clockTolerance, which may be 0.
#Understand a crit header
A producer that lists a header parameter in crit says: don't accept this token unless you understand that parameter. Name the ones your code reads in recognizedHeaders:
/** A token whose `crit` header names `tenant`, so a reader must say it understands it. */
export async function readTenantToken(token: string) {
const { payload, protectedHeader } = await verify(token, publicKey, {
algorithms: ["ES256"],
recognizedHeaders: ["tenant"],
});
return { tenant: protectedHeader.tenant, payload };
}Without recognizedHeaders: ["tenant"], the same token fails with ERR_JWS_INVALID (ERR_JWE_INVALID for decrypt), as RFC 7515 §4.1.11 requires. When you sign, every name in crit must be a parameter the protected header carries.
#Skip the claim checks
validateClaims: false turns off every claim check, exp included, while the signature, typ, crit and algorithms are still checked. Use it for a payload that isn't a JWT, such as a signed webhook body, then check what you need yourself. Leave the claim options out of that call: issuer, audience, subject, maxTokenAge or requiredClaims next to validateClaims: false throws ERR_INVALID_OPTION, because a check that never runs would look like one that passed. A string or bytes payload has no claims, so it's never claim-checked; the same options throw with it, and so does validateClaims: true.
#Check claims that arrived another way
validateJwtClaims runs the same checks on a claims object you already hold, and throws the same codes. computeDurationInSeconds turns a duration into seconds. Both are in unjwt/utils:
import { computeDurationInSeconds, validateJwtClaims } from "unjwt/utils";
validateJwtClaims(claims, { issuer: "https://auth.example.com", maxTokenAge: "1h" });
computeDurationInSeconds("15m"); // 900
computeDurationInSeconds("7D"); // 604800Neither checks a signature: only call validateJwtClaims on claims from a token you already verified.
#When it fails
| Situation | What happens |
|---|---|
exp has passed, or iat is older than maxTokenAge | ERR_JWT_EXPIRED, with cause: { jti, iat, exp }. |
nbf is still in the future | ERR_JWT_NBF. |
iss, sub or aud doesn't match, a time claim isn't a non-negative number, or iat is in the future under maxTokenAge | ERR_JWT_CLAIM_INVALID. |
| A claim the options make required is missing | ERR_JWT_CLAIM_MISSING, naming every missing claim. |
typ doesn't match, or crit names a parameter you didn't recognize | ERR_JWS_INVALID or ERR_JWE_INVALID. |
An option is empty or malformed: issuer: "", maxTokenAge: 0, clockTolerance: -1, "7d" | ERR_INVALID_OPTION, before the token is read. |
A claim option with payload: "string" or "bytes", or with validateClaims: false | ERR_INVALID_OPTION, before the token is read. |
expiresIn with expiresAt, or notBeforeIn with notBeforeAt, when signing | ERR_JWT_CLAIM_INVALID. |
| A time option with a string or bytes payload, when signing | ERR_INVALID_OPTION. |
Handle errors lists every code and what to answer.
#Options
verify, decrypt and their multi variants take these. validateJwtClaims checks the same ones except typ, recognizedHeaders and validateClaims, which need a token around the claims:
| Option | Default | Notes |
|---|---|---|
issuer | none | string or string[]. Makes iss required. |
audience | none | string or string[]. Makes aud required. Without it, aud isn't checked. |
subject | none | Makes sub required. |
typ | none | Compared as a media type with the protected header's typ. |
maxTokenAge | none | A duration. Makes iat required. |
clockTolerance | 0 | Seconds or a duration, applied to exp, nbf and iat. |
currentDate | now | The Date the time claims are compared with. |
requiredClaims | none | Further claim names that must be present. |
recognizedHeaders | none | crit parameters your code understands. |
validateClaims | true for JSON | false skips the claim checks. |
sign and encrypt take the time options: currentDate, issuedAt, expiresIn or expiresAt, notBeforeIn or notBeforeAt.
#Going further
- Per-request checks: Verify a token and Decrypt a token show these options with the key options next to them.
- Sessions: a session's
maxAgebounds both the token'sexpand how long afteriatit's accepted: see Configure a session. cnf: a confirmation key in the payload is never checked for you; compare it with the key the request presents, as DPoP proofs do.