JWT Implementation

Tutorial 1 of 4

JWT Implementation in Express.js: A Comprehensive Guide

1. Introduction

In this tutorial, we are going to implement JWT (JSON Web Token) authentication in an Express.js application. Understanding how to secure your web application by implementing JWT Authentication is a vital skill for any developer.

By the end of this tutorial, you will learn:
- What JWT is and why it is used
- How to generate and verify JWTs
- How to secure your Express.js endpoints using JWT

Prerequisites

  • Basic knowledge of JavaScript and Node.js
  • Familiarity with Express.js
  • Node.js and npm installed on your system

2. Step-by-Step Guide

In JWT Authentication, when the user logs in using their credentials, a JWT is returned. Subsequent requests to the API require this JWT. The server then verifies the JWT sent in the header of the request and if it's valid, processes the request.

We are going to use the jsonwebtoken npm package for this tutorial.

Step 1: Install the necessary packages.

npm install express jsonwebtoken

Step 2: Setup a basic Express.js server

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.json({
        message: 'Welcome to the API'
    });
});

app.listen(3000, () => console.log('Server started on port 3000'));

3. Code Examples

Example 1: Generating a JWT

const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {
  // Mock user
  const user = { id: 3 };

  const token = jwt.sign({ user }, 'your-unique-secret-key');

  res.json({
    token
  });
});

In the code above, the jsonwebtoken is used to sign the user object with a unique secret key. The resulting token is then sent in the response.

Example 2: Verifying a JWT and securing the API

function ensureToken(req, res, next) {
  const bearerHeader = req.headers["authorization"];

  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(" ");
    const bearerToken = bearer[1];
    req.token = bearerToken;
    next();
  } else {
    res.sendStatus(403);
  }
}

app.get('/protected', ensureToken, (req, res) => {
  jwt.verify(req.token, 'your-unique-secret-key', (err, data) => {
    if (err) {
      res.sendStatus(403);
    } else {
      res.json({
        message: 'Protected information. Congrats!',
        data
      });
    }
  });
});

In the above code, ensureToken middleware function checks if there is a token in the authorization header. If not, it sends a 403 status (Forbidden). If there is a token, it's extracted and the request is passed to the next middleware. The '/protected' route is now secured by JWT.

4. Summary

In this tutorial, you learned about:

  • The basics of JWT
  • How to generate and verify a JWT
  • How to secure Express.js endpoints using JWT

Next, you should try implementing JWT Authentication in a full-fledged application. You can explore adding roles to users, restricting access based on roles, and refreshing tokens.

5. Practice Exercises

Exercise 1: Create a '/logout' endpoint that invalidates the JWT.

Exercise 2: Try to implement role-based authorization using JWT.

Exercise 3: Research how to handle token expiration and implement token refreshing.

Remember, practice is key to mastering any concept. Happy coding!