Skip to content

Instantly share code, notes, and snippets.

@seventyeight
Last active January 25, 2023 16:50
Show Gist options
  • Save seventyeight/9f6cbd78bd6dddd07d5600e590f99d4c to your computer and use it in GitHub Desktop.
Save seventyeight/9f6cbd78bd6dddd07d5600e590f99d4c to your computer and use it in GitHub Desktop.
Validate JWS/JWT in nodejs/node
import { createPublicKey, createVerify } from 'node:crypto'
const [header, payload, signature] = token.split('.').map((tokenPart, index) => {
const decoded = Buffer.from(tokenPart, 'base64url').toString();
return index < 2 ? JSON.parse(decoded) : decoded;
})
const key = (await fetch(`${payload.iss}/.well-known/openid-configuration`)
.then((res) => res.json())
.then((config) => fetch(`${config['jwks_uri']}`))
.then((res) => res.json())
.catch((error) => console.error('Error while fetching JWKS', error)))
}
).keys[0]
const pubKey = createPublicKey({ key, format: 'jwk' });
const verify = createVerify('RSA-SHA256'); // if header.alg: 'RS256' doesn't work for HMAC
verify.update(`${token.split('.')[0]}.${token.split('.')[1]}`);
const isValid = verify.verify(pubKey, Buffer.from(token.split('.')[2], 'base64url'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment