Last active
August 5, 2020 20:25
-
-
Save smac89/bd3be40e3024da7a21ff719a40421969 to your computer and use it in GitHub Desktop.
Learning how JWT works
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 crypto from 'crypto'; | |
import assert from 'assert'; | |
const header = {"alg":"HS256","typ":"JWT"}; | |
const payload = {"loggedInAs":"admin","iat":1422779638}; | |
const unsignedToken = Buffer.from(JSON.stringify(header)).toString('base64') + | |
'.' + Buffer.from(JSON.stringify(payload)).toString('base64'); | |
const hmac = crypto.createHmac('sha256', 'secretkey'); | |
hmac.write(unsignedToken); | |
hmac.end(); | |
const sig = hmac.read(); // sig is a hex string | |
console.log(`${unsignedToken}.${sig.toString('base64')}`); | |
// This sig is now stored on the server and can be used to verify a user | |
// once they make any requests | |
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN/oWnFSRgCzcmJmMjLiuyu5CSpyHI="; | |
// verify process | |
const segments = token.split('.'); | |
const [encHeader, encPaylod, encSig] = token.split('.'); | |
const clientHeader = JSON.parse(Buffer.from(encHeader, 'base64').toString()); | |
const clientPayload = JSON.parse(Buffer.from(encPaylod, 'base64').toString()); | |
assert.deepStrictEqual(clientHeader, header); | |
assert.deepStrictEqual(clientPayload, payload); | |
if (crypto.timingSafeEqual(Buffer.from(encSig, 'base64'), sig)) { | |
console.log("Success!"); | |
} else { | |
console.log('Get out!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment