Skip to content

Instantly share code, notes, and snippets.

@BenHall
Created January 4, 2017 11:40
Show Gist options
  • Select an option

  • Save BenHall/ae3111b547a6a0b5e99af93a27dfea57 to your computer and use it in GitHub Desktop.

Select an option

Save BenHall/ae3111b547a6a0b5e99af93a27dfea57 to your computer and use it in GitHub Desktop.
Json Web Tokens Example
var fs = require('fs');
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'blah');
var decoded = jwt.verify(token, 'blah');
console.log("Decodable at https://jwt.io/#debugger", token, decoded.foo); // bar
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
console.log(err);
}
var cert = fs.readFileSync('private.pem'); // get private key
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});
// sign asynchronously
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
console.log(token);
});
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment