Amazon Prime Day August 2020

Create JWT token in Node JS for authentication

JWT stands for JSON Web Token. Most common scenario to use JWT is allowing end users to persist their session information after logging into application. By storing the session information at client side and passing it to the server when making requests for authentication, then server can trust that the enduser is a registered user of the application if it is valid JWT.

Let's say we have a user, trying to log into an application with his login credentials. Once successful they would receive a token that looks like this:

JWT format:

eyJhbGciOpJIUzI1GiIsInR6cCI6IkpXVCJ4.eyJ1c2VybmftZS
I7InVzZXIyIiwiZXhwIjoxNTH3OTc0MDgykQ.3Ye5_w1z5zpD7dSGdRp3S98ZipbNQqmsDRB9vioOx58

This is a JWT, and consists of three parts separated by . (dot)

The first part called header (eyJhbGciOpJIUzI1GiIsInR6cCI6IkpXVCJ4). The header specifies information like the algorithm used to generate the signature. 

The second part is the payload (eyJ1c2VybmftZSI7InVzZXIyIiwiZXhwIjoxNTH3OTc0MDgykQ), which contains application specific information (in our case, this is the username), along with information about the expiry and validity of the token.

The third part is the signature (3Ye5_w1z5zpD7dSGdRp3S98ZipbNQqmsDRB9vioOx58). It is generated by combining and hashing the first two parts along with a secret key.

npm install jsonwebtoken

And import it into your files like so:

const jwt = require('jsonwebtoken');

To sign a token, you will need to have 3 pieces of information:

1. Token secret

2. chunk of data to hash in the token

3. token expiry time

The token secret is a random string used to encrypt and decrypt the data.

const secretVal = 'L+e[F8+j9^GK>Z!)3sGg';

var token = jwt.sign({ id: '123456',aud:'foo:abc',alg:'HS256'}, secretVal, {

    expiresIn: 86400 // expires in 24 hours

  });

  

Verifying a JWT

In order to verify JWT, a signature is once again generated using the header and payload from the incoming JWT, and the secret key. If the signature matches the one on the JWT, then the JWT is considered valid token.

Now let’s pretend that any one trying to issue a fake token. You can easily generate the header and payload, but without knowing the key, there is no way to generate a valid signature. If you try to tamper with the existing payload of a valid JWT, the signatures will no longer match.


jwt.verify(token, secretVal,  { audience: 'foo:abc',algorithms:['HS256'] },function(err, decoded) {

    if (err) {

        console.log({ auth: false, message: 'Failed to authenticate token.',error: err });

    } else {

        id = decoded.id;

    }

  });


Post a Comment

0 Comments