Understanding JWT Authentication with Node.js
Published: 2021-05-22 15:49:06

What is JSON Web Token?
JWT is a stander and secure way to transfer information between parties as a JSON object, that can be verifiable and JWT makes the tokens easy to transfer through an HTTP request.
JWT is mainly used for authentication. After a user signs in to an application, the application then assigns a JWT token to that user. Whenever user will make requests will include the assigned JWT token. This token tells the server what routes, services, and resources the user is allowed to access.
Structure of a JWT
Header — consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512) header.
Payload — Contains the claims that provide information about a user who has been authenticated along with other information such as token expiration time payload
Signature — Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret.
Implement JWT with Node JS
Before you go ahead with this tutorial, you should have knowledge of express framework Here's the Link
for reference.
Create a file called index.js in the project directory. This is the only file that we create and work on in this project in order to keep things simple. Our main goal is to understand how JWTs work in a Node.js application.
So, let’s go ahead and understand what each snippet of code does in this file.
We are importing a couple of modules that we will be needing in the application: express, and JWT. We can install both modules with this command npm i express jsonwebtoken --save from the command line. Then in the index.js file paste the below code 👇.
```
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
app.use(express.json())
```
Now we are going to write a post method with the express, which will help us to create a token.
```
app.post("/api/login", (req, res, next) => {
  const user = {
    id: 1,
    username: "john",
    email: "john@gmail.com"
  };
  const password = '*******'
  if(user.username === req.body.username && password === req.body.password) {
    jwt.sign({ user: user }, "secretkey", (err, token) => {
      res.cookie('token',token);
      res.status(200).json(
          "Auth successful"
        );
    });
  }
  else {
    res.status(401).json('Unauthorized client')
  }
});
// server running
app.listen(process.env.PORT || 3000, () => {
    console.log("Server started with express..");
});
```
! Don’t forget to run the index.js file use this command node index.js
Explanation
sign() method to create a JSON Web Token for that user and returns the token in the form of a JSON string. Now you can make a request through the postman on this URL http://localhost:8000/api/login and the token will save in the cookies
To make sure you got token, you can check in the postman, open postman, and in the top-right side you can click cookies, and then you should get token 👇

you can expand it by click on the token

Finally, we define another post method with verifyToken() that takes care of the token verification process. Let’s see How we can implement

```
app.post("/api/post/verify", (req, res) => {
  let token = req.headers.cookie.split("=")[1]
  jwt.verify(token, "secretkey", (err, authData) => {
    if (err) {
      res.sendStatus(403);
    } else {
      res.json({
        message: "verify successfully.",
        authData
      });
    }
  });
});
```
http://localhost:8000/api/post/verify make a request on it
Explanation
We took the token from our `req.cookies.split("=")[1]` **or** simplest way to get token use this [NPM cookie-parser](https://www.npmjs.com/package/cookie-parser) and then store it in token variable and by the use of .verify() method we are verifying token which we assigned in the previous request
and if the token is valid, will get a message verify successfully on the postman or 403.
HAPPY CODE LIFE
Aadil Raza