In this tutorial, we will focus on implementing JWT (JSON Web Tokens) authentication in a Node.js application. Authentication is an essential part of most web applications, and JWT provides a way to authenticate users in a simple and secure manner.
By the end of this tutorial, you will understand what JWT is, how it works, and how to use it for user authentication in Node.js.
Prerequisites:
You should have a basic understanding of JavaScript and Node.js. Familiarity with Express.js will also be beneficial but not essential as we will cover it in this tutorial.
JWT stands for JSON Web Tokens. It's a standard that allows us to securely transmit data between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
First, we need to set up a new Node.js project. Initialize a new project by running npm init -y
in your terminal.
Next, install the necessary packages: Express.js, JWT, and Bcrypt. Express.js is a minimal web application framework for Node.js, JWT is for creating access tokens, and Bcrypt is for hashing passwords.
npm install express jsonwebtoken bcrypt
Create a new file called index.js
and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
app.listen(3000, () => {
console.log('Server started at http://localhost:3000');
});
Next, let's add JWT authentication to our server. First, we'll create a route for users to register:
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
let users = [];
app.post('/register', async (req, res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const user = { name: req.body.name, password: hashedPassword };
users.push(user);
res.status(201).send();
});
This route accepts a username and password from the request body, hashes the password, and stores it in an array along with the username.
Now, let's create a login route:
app.post('/login', async (req, res) => {
const user = users.find(u => u.name === req.body.name);
if (user == null) {
return res.status(400).send('Cannot find user');
}
try {
if(await bcrypt.compare(req.body.password, user.password)) {
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
res.json({ accessToken: accessToken });
} else {
res.send('Not Allowed');
}
} catch {
res.status(500).send();
}
});
This route finds the user in the array, compares the hashed password with the one provided in the request body, and if they match, it creates and sends a JWT.
In this tutorial, we've explained how JWTs work and how to implement JWT authentication in a Node.js application. We've also provided code examples for setting up an Express.js server and creating routes for registering and logging in.
Next steps would be to learn how to handle JWTs on the client-side, explore different ways of storing JWTs, and using refresh tokens for long-lived sessions.
Here are some additional resources that might be helpful:
- JWT Official Website
- Express.js Documentation
- Node.js Documentation
Solutions:
app.get('/users', (req, res) => {
res.json(users);
});
app.post('/register', async (req, res) => {
const existingUser = users.find(u => u.name === req.body.name);
if(existingUser) {
return res.status(400).send('Username already taken');
}
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const user = { name: req.body.name, password: hashedPassword };
users.push(user);
res.status(201).send();
});
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected route' });
});
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
Tips for further practice: Try implementing a refresh token system and explore different ways of storing tokens such as cookies and local storage.