JWT Verify Expiry And Custom Claims

Parse and verify a JWT signature expiry and custom claims with explicit clock tolerance and audience validation.

JavascriptAuth Jwt

Code

javascriptsnippet
1 line
export async function verifyJWT(token,{secret,tolerance=0,audience}={}){const[header,payload,sig]=token.split('.');const enc=new TextEncoder();const keyObj=await crypto.subtle.importKey('raw',enc.encode(secret),{name:'HMAC',hash:'SHA-256'},false,['verify']);const valid=await crypto.subtle.verify('HMAC',keyObj,base64urlDecode(sig),enc.encode(header+'.'+payload));if(!valid)throw new Error('invalid signature');const claims=JSON.parse(new TextDecoder().decode(base64urlDecode(payload)));const now=Math.floor(Date.now()/1000);if(claims.exp!==undefined&&now>claims.exp+tolerance)throw new Error('token expired');if(audience&&claims.aud!==audience)throw new Error('audience mismatch');return claims;}function base64urlDecode(s){const b64=s.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice(0,(4-s.length%4)%4);return Uint8Array.from(atob(b64),c=>c.charCodeAt(0));}

What the code does

JWT Verify Expiry And Custom Claims is built around the functions verifyJWT and base64urlDecode.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Failure is loud: Error aborts the current operation instead of degrading it.

Caveats

  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard !valid short-circuits the flow with an early throw when its condition holds.

Using it

Signature: export async function verifyJWT(token,{secret,tolerance=0,audience}={})

verifyJWT is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Does the code validate its input?
It throws `Error` before any real work runs, via the guard `!valid` — handle it at the call site or let it propagate deliberately.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `verifyJWT`, `base64urlDecode` at load time.