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.
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.
This tutorial assumes you have basic knowledge of JavaScript and Node.js. Familiarity with the concepts of user authentication and authorization will be beneficial.
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.
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.
// 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.
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.
Use the jsonwebtoken
package to create a JWT that expires in 1 hour. The payload should contain a user ID of your choice.
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.
const jwt = require('jsonwebtoken');
const payload = { userId: 123 };
const secret = 'mysecret';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log(token);
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.