Node.js / Node.js REST APIs

Securing APIs with JWT Authentication

This tutorial explains how to secure your API with JSON Web Token (JWT) authentication. It will guide you through the process of generating tokens on user login and protecting rou…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores creating, testing, and securing RESTful APIs with Node.js and Express.

1. Introduction

In this tutorial, we will be learning how to secure your API with JSON Web Token (JWT) authentication. The goal is to understand how to generate tokens on user login and protecting routes with token verification.

By the end of this tutorial, you will be able to:
- Understand what JWT is and its role in securing APIs
- Generate JWTs on user login
- Protect API endpoints using JWT

Prerequisites:
- Basic understanding of JavaScript and Node.js
- Familiarity with Express.js will be helpful
- Knowledge of RESTful APIs

2. Step-by-Step Guide

2.1 Understanding JWT

JWT stands for JSON Web Token. It is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure.

2.2 Generating JWTs

When a user logs in, we need to generate a JWT that can be sent back to the client for future authentication.

2.3 Protecting Routes

We can use the JWT to make sure that our routes are protected. This means that only requests with a valid token will be able to access certain routes.

3. Code Examples

3.1 Installing Dependencies

Firstly, we need to install the necessary dependencies. We'll use jsonwebtoken for handling JWTs and express for our server.

npm install jsonwebtoken express

3.2 Generating a JWT

Here's an example of how to generate a JWT on user login.

const jwt = require('jsonwebtoken');

// User login
app.post('/login', (req, res) => {
    // In a real application, you'd usually find the user in your database and check their password
    const user = { id: 1, username: 'test' };

    jwt.sign({ user }, 'secret_key', (err, token) => {
        res.json({ token });
    });
});

In the above code, we have a login route that generates a JWT when called. The jwt.sign() function generates the token.

3.3 Protecting Routes

Here's an example of how to protect a route using JWT.

// Middleware for checking JWT
function verifyToken(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);
    }
}

// Protected route
app.post('/api/protected', verifyToken, (req, res) => {
    jwt.verify(req.token, 'secret_key', (err, authData) => {
        if (err) {
            res.sendStatus(403);
        } else {
            res.json({ message: 'This is a protected route', authData });
        }
    });
});

In the above code, we created a middleware function verifyToken that extracts the token from the header. This token is then verified in the protected route. If the token is valid, the protected data is sent back to the client.

4. Summary

In this tutorial, we learned about JWT and how it can be used to secure APIs. We went through how to generate a JWT on user login and how to protect routes using JWT.

For further learning on JWT, you can go through the following resources:
- Official JWT Website
- JWT Authentication Tutorial

5. Practice Exercises

Exercise 1:

Create a registration route that generates a unique JWT for each new user.

Exercise 2:

Create a route that allows a user to change their password and invalidates the JWT on successful password change.

Exercise 3:

Create an application that uses JWT to authenticate users and restricts access to certain routes based on user roles.

Solutions for these exercises will depend on your specific application and database setup. However, the basic principles will remain the same: generate a token when needed, send it back to the client, and check it when a request is made to a protected route.

Keep practicing and exploring more about JWT and other authentication methods!

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

File Size Checker

Check the size of uploaded files.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

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