-
-
Save whaaaley/c4446b2210ed7efaee2a25a1d77f9e86 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
// TODO: | |
// Regex is slow but this is good enough for now | |
// data = string | |
const escape = data => { | |
return data.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') | |
} | |
// data = object | |
const encode = data => { | |
return escape(Buffer.from(JSON.stringify(data)).toString('base64')) | |
} | |
// data = string | |
const decode = data => { | |
return JSON.parse(Buffer.from(data, 'base64').toString()) | |
} | |
module.exports = { escape, encode, decode } |
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
const crypto = require('crypto') | |
const base64url = require('./base64url') | |
// header = string | |
const header = base64url.encode({ alg: 'HS256', typ: 'JWT' }) | |
// data = string, key = string | |
const sign = (data, key) => { | |
return crypto.createHmac('sha256', key).update(data).digest('base64') | |
} | |
// claims = { $string: string || number }, key = string | |
const encode = (claims, key) => { | |
const data = header + '.' + base64url.encode(claims) | |
return data + '.' + base64url.escape(sign(data, key)) | |
} | |
// jwt = string, key = string | |
const verify = (jwt, key) => { | |
const [header, payload, signature] = jwt.split('.') | |
if (signature === base64url.escape(sign(header + '.' + payload, key))) { | |
return { | |
claims: base64url.decode(payload), | |
verified: true | |
} | |
} | |
return { | |
verified: false | |
} | |
} | |
module.exports = { encode, verify } |
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
const jwt = require('./jwt) | |
const secret = crypto.randomBytes(256) | |
const token = encode({ exp: Date.now() + 3600000, sub: 123 }, secret) | |
const { claims, verified } = verify(token, secret) | |
console.log('token', token) | |
console.log('claims', claims) | |
console.log('verified', verified) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment