JWT (JSON Web Tokens) Tutorial 🎯

beginner
12 min

JWT (JSON Web Tokens) Tutorial 🎯

Welcome to the JSON Web Tokens (JWT) tutorial! In this comprehensive lesson, we will explore the ins and outs of this crucial security tool. By the end of this tutorial, you'll have a strong understanding of JWTs, and you'll be able to apply them to your own projects. 💡 Pro Tip: JWTs are widely used for authentication and information exchange between parties, making them a valuable addition to your developer toolkit!

Table of Contents 📝

  1. Introduction to JWT 1.1. What is JWT? 1.2. Why use JWT?

  2. Understanding JWT Structure 2.1. Header 2.2. Payload 2.3. Signature

  3. Creating and Verifying JWTs 3.1. Creating a JWT (Node.js) 3.2. Verifying a JWT (Node.js)

  4. Best Practices and Common Pitfalls 4.1. Securing your JWTs 4.2. Refreshing JWTs 4.3. Expiring JWTs

  5. Real-world Examples 5.1. Implementing JWT Authentication in a Node.js API

1. Introduction to JWT 📝

1.1. What is JWT?

JSON Web Tokens (JWT) are a compact, URL-safe method for representing claims (statements about an individual or a fact) securely between parties. They are often used in web development for authentication and information exchange between a client and server.

1.2. Why use JWT?

JWTs offer several advantages over traditional methods of authentication, such as session-based authentication:

  • Stateless: JWTs do not require a server session, making them scalable and more secure.
  • Flexible: JWTs can contain a wealth of information, allowing for custom claims.
  • Standardized: JWTs are an open standard (RFC 7519) that is widely supported across various platforms and programming languages.

Now that we've covered the basics, let's dive into the structure of JWTs.

2. Understanding JWT Structure 📝

A JWT consists of three parts separated by dots: the header, the payload, and the signature.

2.1. Header

The header contains metadata about the JWT, such as the algorithm used to sign the token. It is base64url-encoded and typically looks like this:

{ "alg": "HS256", "typ": "JWT" }

2.2. Payload

The payload contains the claims (statements) about the user, such as their username, role, or expiration time. It is also base64url-encoded. Here's an example:

{ "sub": "1234567890", "name": "John Doe", "iat": 1639388523, "exp": 1639392123 }

2.3. Signature

The signature ensures that the token is authentic and has not been tampered with. It is generated by combining the header and payload with a secret key (the signing secret) and applying the specified algorithm (e.g., HMAC SHA256).

Now that we understand the structure of a JWT, let's see how to create and verify tokens in Node.js.

3. Creating and Verifying JWTs 📝

3.1. Creating a JWT (Node.js)

javascript
const jwt = require('jsonwebtoken'); const secret = 'mysecret'; const payload = { sub: '1234567890', name: 'John Doe', iat: 1639388523, exp: 1639392123 }; const token = jwt.sign(payload, secret); console.log(token);

3.2. Verifying a JWT (Node.js)

javascript
const jwt = require('jsonwebtoken'); const secret = 'mysecret'; const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; try { const decoded = jwt.verify(token, secret); console.log(decoded); } catch (error) { console.error(error); }

Now that you know how to create and verify JWTs, let's discuss some best practices and common pitfalls.

4. Best Practices and Common Pitfalls 📝

4.1. Securing your JWTs

  • Use strong, unique secrets to sign your tokens.
  • Store secrets securely, ideally in an environment variable.
  • Never share your secret with anyone.

4.2. Refreshing JWTs

  • Implement token refresh mechanisms to extend token lifetimes.
  • Use refresh tokens for long-term authentication.

4.3. Expiring JWTs

  • Set appropriate expiration times for tokens.
  • Use jwt.sign()'s expiresIn option to set token lifetimes.

Now that you've learned the basics of JWTs, let's move on to some real-world examples.

5. Real-world Examples 📝

In this section, we will implement JWT authentication in a Node.js API. You can find the complete code in the CodeYourCraft API authentication tutorial.

5.1. Implementing JWT Authentication in a Node.js API

To authenticate users in a Node.js API, follow these steps:

  1. Install necessary packages:
bash
npm install jsonwebtoken bcryptjs express-jwt
  1. Create a user registration and login route:
javascript
const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const app = express(); app.post('/register', (req, res) => { // Register user logic }); app.post('/login', (req, res) => { // Login user logic });
  1. Implement token-based authentication for protected routes:
javascript
const jwtSecret = 'mysecret'; function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) return res.sendStatus(401); // Unauthorized jwt.verify(token, jwtSecret, (err, user) => { if (err) return res.sendStatus(403); // Forbidden req.user = user; next(); }); } app.get('/protected', authenticateToken, (req, res) => { // Protected route logic });

And that's it! You've now implemented JWT authentication in a Node.js API. You can find more information and examples in the CodeYourCraft API authentication tutorial.

Quick Quiz
Question 1 of 1

What is the purpose of a JWT?

Happy coding! 🎯