Skip to content

Instantly share code, notes, and snippets.

@deskoh
Created May 3, 2020 23:19
Show Gist options
  • Select an option

  • Save deskoh/9bab069296cf4eaaa683a77659155e76 to your computer and use it in GitHub Desktop.

Select an option

Save deskoh/9bab069296cf4eaaa683a77659155e76 to your computer and use it in GitHub Desktop.
Asymmetric JWTs
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