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!
Introduction to JWT 1.1. What is JWT? 1.2. Why use JWT?
Understanding JWT Structure 2.1. Header 2.2. Payload 2.3. Signature
Creating and Verifying JWTs 3.1. Creating a JWT (Node.js) 3.2. Verifying a JWT (Node.js)
Best Practices and Common Pitfalls 4.1. Securing your JWTs 4.2. Refreshing JWTs 4.3. Expiring JWTs
Real-world Examples 5.1. Implementing JWT Authentication in a Node.js API
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.
JWTs offer several advantages over traditional methods of authentication, such as session-based authentication:
Now that we've covered the basics, let's dive into the structure of JWTs.
A JWT consists of three parts separated by dots: the header, the payload, and the signature.
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"
}
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
}
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.
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);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.
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.
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.
To authenticate users in a Node.js API, follow these steps:
npm install jsonwebtoken bcryptjs express-jwtconst 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
});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.
What is the purpose of a JWT?
Happy coding! 🎯