In this tutorial, we will learn about JSON Web Tokens (JWT) and how to implement JWT Authentication in your application. JWT is a standard for securely transmitting information as a JSON object. This information can be verified and trusted because it is digitally signed.
By the end of this tutorial, you will be able to:
- Understand what JWT is and why it's used for authentication.
- Implement JWT authentication in your application.
- Securely transmit user information as a JSON object.
To follow this tutorial, you should have a basic understanding of:
- JavaScript (specifically Node.js and Express.js)
- REST APIs
- User authentication and authorization
JWT stands for JSON Web Token. It's 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, enabling the claims to be digitally signed.
When a user logs in, the server creates a unique token associated with that user and sends it back to the user. The client will then include the token in the header of every request. The server can then verify the token and respond with data for that user.
We will use jsonwebtoken
to sign and verify tokens, and express-jwt
to validate tokens and protect routes.
npm install jsonwebtoken express-jwt
Use jsonwebtoken
to sign and verify tokens. Here's an example:
const jwt = require('jsonwebtoken');
const data = {
id: 1,
username: 'testuser',
};
const secret = 'your-own-secret-key';
const token = jwt.sign(data, secret, { expiresIn: '1h' });
console.log('Token:', token);
try {
const decoded = jwt.verify(token, secret);
console.log('Decoded:', decoded);
} catch (err) {
console.error('Error:', err);
}
Use express-jwt
to validate tokens and protect routes. Here's an example:
const express = require('express');
const jwt = require('express-jwt');
const app = express();
const secret = 'your-own-secret-key';
app.use(jwt({ secret }));
app.get('/', (req, res) => {
res.send('You are authenticated'); // if JWT is valid, this will be sent
});
app.listen(3000, () => console.log('Server started on 3000'));
Here's how to sign a token with user data:
const jwt = require('jsonwebtoken');
const user = {
id: 1,
username: 'testuser',
};
const secret = 'your-own-secret-key';
const token = jwt.sign(user, secret, { expiresIn: '1h' });
console.log('Token:', token);
Here's how to verify the token:
const jwt = require('jsonwebtoken');
const token = 'your-jwt-token';
const secret = 'your-own-secret-key';
try {
const decoded = jwt.verify(token, secret);
console.log('Decoded:', decoded);
} catch (err) {
console.error('Error:', err);
}
We have learned what JWT is, why it is used for authentication, and how to implement JWT authentication in our applications. You can now securely transmit user data as a JSON object and use it for authentication and authorization purposes.
Exercise: Create a login route that signs a JWT with user data and sends it back to the client.
Exercise: Create a middleware function that verifies the JWT and attaches the user data to the request object.
Exercise: Protect a route with your middleware function. Test it with and without the JWT.
Tip: You can use tools like Postman to test your API endpoints. You can also use online JWT decoders to see the content of your tokens.