Created
January 26, 2017 02:47
-
-
Save miguelmota/80d140ab31b0aeeed326aa5bd5e55c20 to your computer and use it in GitHub Desktop.
JSON Web Tokens Node.js generate and verify
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
| const {TokenVerifier} = require('jsontokens'); | |
| const {randomBytes, createHash} = require('crypto'); | |
| const secp256k1 = require('secp256k1'); | |
| function signer(privateKey, data) { | |
| const hash = createHash(`sha256`).update(data).digest(); | |
| const signature = secp256k1.sign(hash, privateKey).signature.toString('base64'); | |
| return signature; | |
| } | |
| function base64(data) { | |
| return new Buffer(data, 'utf8').toString('base64'); | |
| } | |
| const privateKey = randomBytes(32); | |
| const header = { | |
| "alg": "HS256", | |
| "typ": "JWT" | |
| }; | |
| const b64Header = base64(JSON.stringify(header)); | |
| const body = { | |
| "sub": "1234567890", | |
| "name": "John Doe", | |
| "admin": true | |
| }; | |
| const b64Body = base64(JSON.stringify(body)); | |
| const data = new Buffer(`${b64Header}.${b64Body}`); | |
| const signature = signer(privateKey, data); | |
| const token = `${data}.${signature}`; | |
| const publicKey = secp256k1.publicKeyCreate(privateKey).toString('hex'); | |
| const verified = new TokenVerifier('ES256k', publicKey).verify(token); | |
| console.log(verified); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment