Understanding Token-Based Authentication with JSON Web Tokens (JWT) in Express.js
Tags: webdev, javascript, jwt
Published: 2024-04-08 06:51:12

**Introduction**:
Authentication is a critical aspect of web applications, ensuring that only authorized users can access sensitive data and functionalities. Among various authentication methods, token-based authentication stands out for its simplicity and effectiveness. In this article, we'll delve into token-based authentication using JSON Web Tokens (JWT) in an Express.js application.

**Why Authentication Matters**:
Authentication safeguards sensitive user data from unauthorized access. Without proper authentication mechanisms, anyone could access confidential information, posing significant security risks.

**What is Authentication?**:
Authentication is the process of verifying the identity of a user. It typically involves combining a username and password to validate user credentials before granting access to resources.

**Common Authentication Methods**:

- Password-based authentication
- Token-based authentication
- Cookie-based authentication
- OAuth-based authentication
- Token-Based Authentication with JWT

**Let us understand the Token-Based Authentication**:
JWT, or JSON Web Token, is a compact, URL-safe means of representing claims to be transferred between two parties securely. It consists of three parts: header, payload, and signature.

**JWT has three parts seperated by dots(.)**

-  Header - It has the JWT and the signing algorithm
-  payload - It is just data which used to create the JWT
-  signature - It is a kind of password to verify the JWT


![JWT Working](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a66gp261o15iori46hx7.png)

- The user sends a request to authenticate (e.g., /signin) with their credentials.
- Upon successful validation, the server generates a JWT containing relevant user information.
- The client receives the JWT and includes it in subsequent requests to access protected resources.
- The server verifies the JWT's signature to ensure its authenticity and grants access to authorized resources.

**Implementing JWT in Express.js**:
We can integrate JWT seamlessly into Express.js applications using the jsonwebtoken library. Here's a step-by-step guide:

- Install the jsonwebtoken library: npm install jsonwebtoken
- Import the library into your application.
- Utilize the provided methods (jwt.sign() and jwt.verify()) to manage JWTs.

```
const jwt = require('jsonwebtoken);
const jwtPassword = '12345678'

const user = {
	userName : "Tirth",
	password : "test@123"
}

//create the JWT

const token = jwt.sign({username : user.userName}, jwtPassword);
//token is nothing but very long string
//verify the token
const data = jwt.verify(token, jwtPasssword);
//data --> {
//	username : "Tirth" }
//
```
In above code, I just explain how to manage JWT. 

**Example Implementation:**
We'll walk through a basic Express.js application demonstrating token-based authentication:

```
const express = require("express");
const jwt = require("jsonwebtoken");
const jwtPassword = "123456";

const app = express();
app.use(express.json())

const ALL_USERS = [
  {
    username: "harkirat@gmail.com",
    password: "123",
    name: "harkirat singh",
  },
  {
    username: "raman@gmail.com",
    password: "123321",
    name: "Raman singh",
  },
  {
    username: "priya@gmail.com",
    password: "123321",
    name: "Priya kumari",
  },
];

function userExists(username, password) {
  // write logic to return true or false if this user exists
  // in ALL_USERS array
const userFind = ALL_USERS.filter(user => user.username === username && user.password === password);

return userFind.lenght > 0 ?false:true


}

app.post("/signin", function (req, res) {
  const username = req.body.username;
  const password = req.body.password;

  if (!userExists(username, password)) {
    return res.status(403).json({
      msg: "User doesnt exist in our in memory db",
    });
  }

  var token = jwt.sign({ username: username }, jwtPassword);
  return res.json({
    token,
  });
});

app.get("/users", function (req, res) {
  const token = req.headers.authorization;
  try {
    const decoded = jwt.verify(token, jwtPassword);
    const username = decoded.username;
    console.log(decoded)
    const filteredUser = ALL_USERS.filter((user) => user.username != username)
    res.json({
        userdata : filteredUser
    })
    // return a list of users other than this username
  } catch (err) {
    return res.status(403).json({
      msg: "Invalid token",
    });
  }
});

app.listen(3001)
```
Above code implements a basic sign-in system that allows users to authenticate and obtain a JWT upon successful login. The JWT can then be used to access authorized resources (like the /users endpoint) that require authentication. 

**Conclusion**:
Token-based authentication using JSON Web Tokens provides a secure and efficient method for authenticating users in web applications. By understanding the principles behind JWT and its implementation in Express.js, developers can enhance the security of their applications while providing a seamless user experience.

To learn more about the JWT please visit below link:
https://www.npmjs.com/package/jsonwebtoken
https://jwt.io/

Thank you so much for reading the Blog.