Working with JSON Web Tokens

Tutorial 5 of 5

1. Introduction

1.1 Brief explanation of the tutorial's goal

JSON Web Tokens (JWTs) are a popular method to securely transmit information between parties as a JSON object. In this tutorial, we will cover the basics of how to work with JWTs, including how to create, validate, and use them.

1.2 What the user will learn

You will learn about the structure of JWTs, how to create a token, how to validate a token, and how to extract information from a token.

1.3 Prerequisites

This tutorial assumes you have basic knowledge of JavaScript and Node.js. Familiarity with the concepts of user authentication and authorization will be beneficial.

2. Step-by-Step Guide

2.1 Detailed explanation of concepts

A JWT is composed of three parts: a header, a payload, and a signature. The header typically contains the type of token and the signing algorithm used. The payload contains the claims, which are statements about the user and additional data. The signature is used to verify that the sender of the JWT is who they say they are and to ensure that the message wasn't changed during transit.

2.2 Clear examples with comments

Let's consider an example where we want to create a JWT. We will use the jsonwebtoken package in Node.js. First, install it using npm:

npm install jsonwebtoken

Next, let's create a token:

const jwt = require('jsonwebtoken');
const payload = { user: 'John Doe' };
const secret = 'mysecret';

const token = jwt.sign(payload, secret);

In this example, we're creating a token using the jwt.sign() method. We pass in the payload and the secret as parameters.

2.3 Best practices and tips

  • Always keep your secret key secret! If it is compromised, others can issue tokens pretending to be you.
  • Don't put sensitive information in the payload or header of a JWT because it can be decoded by anyone.
  • JWTs are not encrypted, so don't trust the information in them without verifying it first.

3. Code Examples

3.1 Example: Creating and validating JWT tokens

// Creating a JWT
const jwt = require('jsonwebtoken');
const payload = { user: 'John Doe' };
const secret = 'mysecret';

const token = jwt.sign(payload, secret);
console.log(token);

// Validating a JWT
jwt.verify(token, secret, (err, decoded) => {
  if (err) {
    console.log('Token could not be verified');
  } else {
    console.log('Decoded payload:', decoded);
  }
});

In this example, we first create a token and print it. Then we verify the token using jwt.verify(). If the token is valid, it will print the decoded payload; otherwise, it will print an error message.

4. Summary

In this tutorial, we learned about JWTs, their structure, and how to create and validate them. We also discussed some best practices to follow when using JWTs.

5. Practice Exercises

5.1 Exercise: Create a JWT with an expiry time

Use the jsonwebtoken package to create a JWT that expires in 1 hour. The payload should contain a user ID of your choice.

5.2 Exercise: Extracting information from a JWT

Write a function that takes a JWT and a secret as parameters. It should validate the token and return the user ID from the payload.

Solutions

5.1 Solution

const jwt = require('jsonwebtoken');
const payload = { userId: 123 };
const secret = 'mysecret';

const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log(token);

5.2 Solution

function getUserIdFromToken(token, secret) {
  jwt.verify(token, secret, (err, decoded) => {
    if (err) {
      console.log('Token could not be verified');
    } else {
      console.log('User ID:', decoded.userId);
    }
  });
}

In these exercises, we practiced creating a JWT with an expiry time and extracting information from a JWT's payload. For further practice, try creating JWTs with different payloads and options.