Securing APIs with JWT Authentication

Tutorial 4 of 5

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!