Created
May 3, 2020 23:19
-
-
Save deskoh/9bab069296cf4eaaa683a77659155e76 to your computer and use it in GitHub Desktop.
Asymmetric JWTs
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
| var assert = require('assert') | |
| var crypto = require('crypto') | |
| var jose = require('jose') | |
| var jws = require('jws') | |
| var convert = require('jwk-to-pem') | |
| var { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { | |
| modulusLength: 4096, | |
| publicKeyEncoding: { | |
| type: 'spki', | |
| format: 'pem' | |
| }, | |
| privateKeyEncoding: { | |
| type: 'pkcs8', | |
| format: 'pem', | |
| // cipher: 'aes-256-cbc', // optional | |
| // passphrase: 'top secret' // optional | |
| } | |
| }) | |
| var jwk = jose.JWK.asKey(publicKey) | |
| var jwt = jws.sign({ | |
| header: {typ: 'JWT', alg: 'RS256', kid: jwk.kid}, | |
| payload: { | |
| iss: 'http://localhost:5000', | |
| aud: 'key', | |
| iat: Math.floor(Date.now() / 1000) - 5, | |
| exp: Math.floor(Date.now() / 1000) + 5, | |
| }, | |
| secret: privateKey | |
| }) | |
| var public_key = convert(jwk) | |
| assert(publicKey === public_key) | |
| var decodedJwt = jws.decode(jwt) | |
| assert(jws.verify(jwt, decodedJwt.header.alg, public_key)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment