Last active
January 6, 2022 17:03
-
-
Save samuelkarani/7d84f6755dbed07af2188091a6632ead to your computer and use it in GitHub Desktop.
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
//Original Reference: https://guseyn.com/posts/simple-jwt | |
function payloadWithExpirationTime (payload, minutesFromNow) { | |
let date = new Date() | |
date.setMinutes(date.getMinutes() + minutesFromNow) | |
payload.exp = date.getTime() | |
return payload | |
} | |
function base64UrlEncodeJSON (json) { | |
return Buffer.from( | |
JSON.stringify(json) | |
).toString('base64') | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
} | |
const crypto = require('crypto') | |
function generateSignature (str, secret) { | |
return crypto | |
.createHmac('sha256', secret) | |
.update(str) | |
.digest('base64') | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
} | |
const encodedHeaderInBase64 = base64UrlEncodeJSON(header) | |
const encodedPayloadInBase64 = base64UrlEncodeJSON(payload) | |
const encodedSignatureInBase64 = generateSignature(`${encodedHeaderInBase64}.${encodedPayloadInBase64}`, 'some-secret') | |
const token = `${encodedHeaderInBase64}.${encodedPayloadInBase64}.${encodedSignatureInBase64}` | |
// Returns true if token is valid, otherwise returns false | |
function isValid (token, secret) { | |
const parts = token.split('.') | |
const header = base64UrlDecodeToJSON(parts[0]) | |
const payload = base64UrlDecodeToJSON(parts[1]) | |
if (header.alg !== 'HS256' || header.typ !== 'JWT') { | |
return false | |
} | |
const signature = parts[2] | |
const exp = payload.exp | |
if (exp) { | |
if (exp < new Date().getTime()) { | |
return false | |
} | |
} | |
return generateSignature(`${parts[0]}.${parts[1]}`, secret) === signature | |
} | |
function base64UrlDecodeToJSON (str) { | |
return JSON.parse( | |
Buffer.from( | |
str.replace(/-/g, '+').replace(/_/g, '/'), 'base64' | |
).toString('utf8') | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment