Last active
April 28, 2024 12:19
-
-
Save afraz-khan/4c7afd180f5f4a4098eb01339c163c40 to your computer and use it in GitHub Desktop.
Calculate HMAC for JWT Signature (TypeScript/NodeJS)
This file contains hidden or 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 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