Last active
January 25, 2023 16:50
-
-
Save seventyeight/9f6cbd78bd6dddd07d5600e590f99d4c to your computer and use it in GitHub Desktop.
Validate JWS/JWT in nodejs/node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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