Skip to content

Instantly share code, notes, and snippets.

@afraz-khan
Last active April 28, 2024 12:19
Show Gist options
  • Save afraz-khan/4c7afd180f5f4a4098eb01339c163c40 to your computer and use it in GitHub Desktop.
Save afraz-khan/4c7afd180f5f4a4098eb01339c163c40 to your computer and use it in GitHub Desktop.
Calculate HMAC for JWT Signature (TypeScript/NodeJS)
import crypto from 'crypto';
export class JwtTokenVerifier {
verifyToken(token: string) {
const [headerEncoded, payloadEncoded, signature] = token.split('.');
const header = this.decodeBase64ToAscii(headerEncoded);
const payload = this.decodeBase64ToAscii(payloadEncoded);
// Other validation checks here
// Validate the token signature, ref ==> https://jwt.io/
if (this.hmachWithSHA256(`${headerEncoded}.${payloadEncoded}`) !== signature){
throw new Error('Token is invalid.')
}
return True;
}
private hmacWithSha256(input: string) {
const hash = crypto.createHmac('sha256', "${secretKey}");
hash.update(input, 'utf8');
return hash.digest('base64url');
}
private decodeBase64ToAscii(encoded: string) {
const buff = Buffer.from(encoded, 'base64');
const text = buff.toString('ascii');
return JSON.parse(text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment