Implementing JWT Authentication in Node.js

Tutorial 1 of 5

1. Introduction

In this tutorial, we will focus on implementing JWT (JSON Web Tokens) authentication in a Node.js application. Authentication is an essential part of most web applications, and JWT provides a way to authenticate users in a simple and secure manner.

By the end of this tutorial, you will understand what JWT is, how it works, and how to use it for user authentication in Node.js.

Prerequisites:
You should have a basic understanding of JavaScript and Node.js. Familiarity with Express.js will also be beneficial but not essential as we will cover it in this tutorial.

2. Step-by-Step Guide

2.1 Understanding JWT

JWT stands for JSON Web Tokens. It's a standard that allows us to securely transmit data between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

2.2 Setup

First, we need to set up a new Node.js project. Initialize a new project by running npm init -y in your terminal.

Next, install the necessary packages: Express.js, JWT, and Bcrypt. Express.js is a minimal web application framework for Node.js, JWT is for creating access tokens, and Bcrypt is for hashing passwords.

npm install express jsonwebtoken bcrypt

3. Code Examples

3.1 Creating the Express Server

Create a new file called index.js and add the following code:

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

app.listen(3000, () => {
  console.log('Server started at http://localhost:3000');
});

3.2 Adding JWT Authentication

Next, let's add JWT authentication to our server. First, we'll create a route for users to register:

const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
let users = [];

app.post('/register', async (req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  const user = { name: req.body.name, password: hashedPassword };
  users.push(user);
  res.status(201).send();
});

This route accepts a username and password from the request body, hashes the password, and stores it in an array along with the username.

Now, let's create a login route:

app.post('/login', async (req, res) => {
  const user = users.find(u => u.name === req.body.name);
  if (user == null) {
    return res.status(400).send('Cannot find user');
  }
  try {
    if(await bcrypt.compare(req.body.password, user.password)) {
      const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
      res.json({ accessToken: accessToken });
    } else {
      res.send('Not Allowed');
    }
  } catch {
    res.status(500).send();
  }
});

This route finds the user in the array, compares the hashed password with the one provided in the request body, and if they match, it creates and sends a JWT.

4. Summary

In this tutorial, we've explained how JWTs work and how to implement JWT authentication in a Node.js application. We've also provided code examples for setting up an Express.js server and creating routes for registering and logging in.

Next steps would be to learn how to handle JWTs on the client-side, explore different ways of storing JWTs, and using refresh tokens for long-lived sessions.

Here are some additional resources that might be helpful:
- JWT Official Website
- Express.js Documentation
- Node.js Documentation

5. Practice Exercises

  1. Exercise 1: Create a route that returns all registered users.
  2. Exercise 2: Add error handling for cases where the username is already taken during registration.
  3. Exercise 3: Implement a route that requires a valid JWT to access.

Solutions:

  1. Solution 1: See this example code for returning all users:
app.get('/users', (req, res) => {
  res.json(users);
});
  1. Solution 2: Check if the username already exists during registration:
app.post('/register', async (req, res) => {
  const existingUser = users.find(u => u.name === req.body.name);
  if(existingUser) {
    return res.status(400).send('Username already taken');
  }
  const hashedPassword = await bcrypt.hash(req.body.password, 10);
  const user = { name: req.body.name, password: hashedPassword };
  users.push(user);
  res.status(201).send();
});
  1. Solution 3: Use JWT to protect a route:
app.get('/protected', authenticateToken, (req, res) => {
  res.json({ message: 'This is a protected route' });
});

function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (token == null) return res.sendStatus(401);
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

Tips for further practice: Try implementing a refresh token system and explore different ways of storing tokens such as cookies and local storage.