Express.js / REST APIs with Express.js

Securing REST APIs with JWT Authentication

This tutorial will guide you through securing your API using JWT (JSON Web Tokens) authentication. You'll learn about the basics of JWT, how to implement it in Express.js, and how…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explores building RESTful APIs using Express.js and best practices for API design.

Introduction

In this tutorial, we'll explore how to secure your RESTful API using JWT (JSON Web Tokens). JWT is a self-contained method for securely transmitting information between parties. It's a popular choice for handling user authentication and authorization in web applications.

By the end of this tutorial, you'll understand the basics of JWT, how to implement JWT authentication in an Express.js application, and how to protect your API routes using JWT.

Prerequisites for this tutorial include a basic understanding of JavaScript and familiarity with Node.js and Express.js.

Step-by-Step Guide

  1. JSON Web Tokens (JWT)

JWTs are encoded JSON objects, which are digitally signed. They can be verified and trusted because they are signed. JWTs can be encrypted to also provide secrecy between parties. JWTs are used for authentication and secure information exchange.

  1. JWT Structure

JWTs are composed of three parts: header, payload, and signature. They are separated by periods (.) and look like this: xxxx.yyyy.zzzz.

  1. Implementing JWT in Express.js

We'll use the jsonwebtoken package to handle JWT in our Express.js app. Install it using npm:

npm install jsonwebtoken

Code Examples

  1. Creating a JWT

Here's how you can create a JWT in an Express.js application:

const jwt = require('jsonwebtoken');
const user = { id: 1, username: 'test' };

const accessToken = jwt.sign(user, 'secretKey', { expiresIn: '1h' });

console.log(accessToken);

In this example, jwt.sign() creates a new JWT. The first parameter is the payload (user object), the second is a secret key, and the third is an options object where we specify the token's lifetime.

  1. Verifying a JWT

To verify a JWT, we use jwt.verify():

const data = jwt.verify(accessToken, 'secretKey');
console.log(data);

If the token is valid, jwt.verify() will return the payload.

Summary

In this tutorial, we covered the basics of JWT and how to implement JWT authentication in an Express.js application. We learned how to create and verify JWTs and how to secure API routes using JWT.

To continue learning about JWT and Express.js, consider exploring how to handle errors when verifying tokens and how to refresh tokens when they expire.

Practice Exercises

  1. Creating a JWT

Create a JWT with a payload containing an object { id: 2, username: 'test2' }. Set the token's lifetime to 2 hours.

  1. Verifying a JWT

Verify the token you created in the first exercise. What's the output?

  1. Securing an API Route

Create an Express.js application with a single protected API route. The route should return a message "Hello, [username]!" where [username] is the username from the JWT payload. Use the JWT from the first exercise to access this route.

Solutions

  1. Creating a JWT:
const user = { id: 2, username: 'test2' };
const accessToken = jwt.sign(user, 'secretKey', { expiresIn: '2h' });
console.log(accessToken);
  1. Verifying a JWT:
const data = jwt.verify(accessToken, 'secretKey');
console.log(data);

The output will be the payload of the token: { id: 2, username: 'test2', iat: [timestamp], exp: [timestamp] }.

  1. Securing an API Route:
const express = require('express');
const app = express();

app.get('/protected', (req, res) => {
  const token = req.headers['authorization'];
  if (!token) return res.status(401).send('Access Denied');

  try {
    const data = jwt.verify(token, 'secretKey');
    res.send(`Hello, ${data.username}!`);
  } catch {
    res.status(401).send('Invalid Token');
  }
});

app.listen(3000);

In this solution, we first check if the request contains a token. If not, we return a 401 status. If a token is present, we attempt to verify it. If verification is successful, we send a personalized message to the user. Otherwise, we return a 401 status.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Unit Converter

Convert between different measurement units.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help