JSON Web Tokens offer a simple and powerful way to generate tokens for APIs which can be consumed during communication from frontend applications, mobile devices, IOT devices or even from other server communication i.e server to server communication. These tokens carry a payload that is cryptographically signed. While the payload itself is not encrypted, the signature protects it again tampering.

There are basically two ways for the use of secret keys i.e

  1. You can use single key for both sign and verify.
  2. You can use asymetric concept of public and private keys, this concept is widely used in microservices. (we are going to discuss it)

Asymetric Keys – Private and Public Keys

Private Keys – Are used for generating the token, this key only resides on Authentication or Token Generator Application.

Private Keys – Are used for verifications and these are distributed to all the microservices.

Lets Install jsonwebtoken in NodeJS

npm i jsonwebtoken

Now visit any online public-private key generator website to generate keys or you can use PuttyGen to generate keys

Generating Asymetric Keys – After generating save public and private keys

Your Keys looks like

-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAMe2LePjGfd0PMKTP2xWf9V7DN1bC1nJzn+ZTKo0nWIyFxIHI9mt
M8rnAntNzQGsh+BZ0+gbcAobQ1asGvPZ3GcCAwEAAQJAWRzOT0BXptYkAoJnq3TR
Z7WXYPIuF2t4C/GghtYhX93Fa3MYf0+AsToGp7EzT1Q+Crxn4s7NMwtYbyzsvlF8
MQIhAPZi+R/88nRLhbY4OPXcf4kkBqJQHyfO/fZGCdyeLOq5AiEAz4D+hUODTrXe
bpKEwSZjRJ7xHVfhh3bOBvuYHZU88B8CIQDX9BPrR6ey6ub9ufWi+WsHZv4xkgxc
tf6+ttC6ACHacQIgMUDpKTCxRkmdFpnosQAvp+YiTVjCy6jDlpy5qqv13vkCIQDD
K0ABX80X945LR+n2Ka6WKnKOyMtXVMuPbllnN6TJjQ==
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMe2LePjGfd0PMKTP2xWf9V7DN1bC1nJ
zn+ZTKo0nWIyFxIHI9mtM8rnAntNzQGsh+BZ0+gbcAobQ1asGvPZ3GcCAwEAAQ==
-----END PUBLIC KEY-----

Now copy same both the keys in public.key and private.key

Now lets come back to jsonwebtoken

Generate Token

var privateKey = fs.readFileSync('private.key' );

var payload = {
    key1: "Data 1",
    key2: "Data 2",
    key3: "Data 3"
   };

var signOptions = {
    issuer:  'issuer name',
    subject:  'subject',
    audience:  'audience',
    expiresIn: 'time in millisecond or m,h,d,y format',
    algorithm:  ['Algorithm name like RS256']
   };

jwt.sign(payload, privateKEY, signOptions, (err, token)=> {
       if(err) {
           console.log(err.message);
       } else {
          console.log("Congrats your token is : " + token);
      }
});

Verify Token

var publicKey = fs.readFileSync('public.key');

var verifyOptions= {
    issuer:  'issuer name',
    subject:  'subject',
    audience:  'audience',
    expiresIn: 'time in millisecond or m,h,d,y format',
    algorithm:  ['Algorithm name like RS256']
   };

jwt.verify(token, publicKEY, verifyOptions, (err, dataInPayload)=> {
       if(err) {
           console.log(err.message);
       } else {
          console.log('data in payload : ', dataInPayload);
      }
});

Congrats You have successfully generate and verified jsonwebtoken