How to use JSON web tokens with Node.js ?

JSON Web Token (JWT) is an Internet Standard that is used for exchanging data between two parties in a secure manner. It can’t be easily hacked as it creates a digital signature with the secret key along with the HMAC algorithm). 
JWT Structure: JSON Web Tokens consist of three parts separated by dots (xxxxx.yyyyy.zzzzz), which are:

Header: This contains the type of the token (JWT in this case) and the algorithm used.

Payload: This contains the payload data that was used while creating the token

Signature: The digital signature that is created using the header, payload, and secret key along with an algorithm as specified in the header).

Integration with Node.js: 
Step 1: First up, initialize a simple node app using the below command and add express, dotenv package.
npm init -y npm i express dotenv
Step 2: Then, install JWT using the below command
npm i jsonwebtoken

JWT_SECRET_KEY = gfg_jwt_secret_keyTOKEN_HEADER_KEY = gfg_token_header_key

app.post(“/user/generateToken”, (req, res) => {
// Validate User Here
// Then generate JWT Token

let jwtSecretKey = process.env.JWT_SECRET_KEY;
let data = {
    time: Date(),
    userId: 12,
}

const token = jwt.sign(data, jwtSecretKey);

res.send(token);

});

app.get(“/user/validateToken”, (req, res) => {
// Tokens are generally passed in the header of the request
// Due to security reasons.

let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;
let jwtSecretKey = process.env.JWT_SECRET_KEY;

try {
    const token = req.header(tokenHeaderKey);

    const verified = jwt.verify(token, jwtSecretKey);
    if(verified){
        return res.send("Successfully Verified");
    }else{
        // Access Denied
        return res.status(401).send(error);
    }
} catch (error) {
    // Access Denied
    return res.status(401).send(error);
}

});

Leave a comment

Your email address will not be published. Required fields are marked *