Using JSON Web Tokens for authentication in NodeJS

Table of contents

No heading

No headings in the article.

When we are creating a website that requires user authentication and authorization and then only show the protected data to the user there are several ways to do that.

1) Local Storage

2) Session Storage

3) HttpOnly Cookies

Firstly we have to create an access token and the we can use any of the above methods to authorize the user. In this article we will only see how to store access token in cookies and how to authorize the user. We can create the access token using the npm package 'jsonwebtoken'. We can install tha npm package by


npm i jsonwebtoken

Let's Code First step is to create a server for handling our routes

const express = require("express");

const app = express();
const port = 5000;

app.get("/", (req, res) => {
  return res.json({ message: "Hello World" });
});


app.listen(port,()=>{console.log(`Server running on port ${port}`)});

We have created a server with a home route('/') which gives response of Hello World.

Now we will import the dependency jsonweb token as const jwt = require("jsonwebtoken");

Now we will create a "/login" route. When user login he will get the access token and it will get stored in cookies for authorization. In this we will also create the jwt access token.

app.get("/login", (req, res) => {
  const token = jwt.sign({ id: 7, role: "captain" }, "YOUR_SECRET_KEY");
  return res
    .cookie("access_token", token, {
      httpOnly: true,
    })
    .status(200)
    .json({ message: "Logged in successfully" });
});

We have successfully created and stored our jwt token as "access_token" in cookies as httpCookies only.

Now we are able to create a JWT, so we already have the authentication finalized. But the authorization is missing. So we are going to create a middleware called auth to check if the request has a JWT or not. If not, access to the controller will be denied, protecting it.

const auth = (req, res, next) => {
  const token = req.cookies.access_token;
  if (!token) {
    return res.sendStatus(403);
  }
  try {
    const data = jwt.verify(token, "YOUR_SECRET_KEY");
    req.userId = data.id;
    req.userRole = data.role;
  } catch {
    return res.sendStatus(403);
  }
};

After authorization user will get his id token and his role as response.

Now we just need to create route. This route can only be accessed if we have access to the jwt that is inside the cookie. If we don't, we will get an error. And now we will be able to make use of the new properties that we added to the request.

app.get("/protected", authorization, (req, res) => {
  return res.json({ user: { id: req.userId, role: req.userRole } });
});

Now this time we are going to crete our logout route. Basically when the user logout's the token in cookie will get cleared and user will not be able to get the protected route.

app.get("/logout", authorization, (req, res) => {
  return res
    .clearCookie("access_token")
    .status(200)
    .json({ message: "Successfully logged ou" });
});