JWT (JSON Web Tokens) is a popular method to handle authentication in web applications.
It provides a secure way to verify users and authorize access to resources. Here’s a step-by-step guide to set up JWT authentication in an Express.js application.
Step 1: Install Dependencies
To get started, you’ll need the following npm packages:
npm install express jsonwebtoken bcryptjs body-parser
- express: Framework to build the server.
- jsonwebtoken: For creating and verifying JWTs.
- bcryptjs: To hash passwords for secure storage.
Step 2: Create an Express App
Set up a simple Express app:
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const users = []; // Placeholder for user storage
const secretKey = 'yourSecretKey'; // Secret key for signing the JWT
Step 3: User Registration Route
Create a route to register users, where passwords are hashed using bcryptjs
:
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ username, password: hashedPassword });
res.json({ message: 'User registered successfully!' });
});
Step 4: User Login Route
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) {
return res.status(400).json({ message: 'User not found' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(400).json({ message: 'Invalid password' });
}
const token = jwt.sign({ username: user.username }, secretKey, { expiresIn: '1h' });
res.json({ token });
});
Step 5: Protect Routes with JWT
To protect routes, you can create a middleware that checks the validity of the token:
const authenticateToken = (req, res, next) => {
const token = req.header('Authorization')?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Access Denied' });
}
jwt.verify(token, secretKey, (err, user) => {
if (err) {
return res.status(403).json({ message: 'Invalid Token' });
}
req.user = user;
next();
});
};
Use this middleware to protect any routes:
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: `Hello, ${req.user.username}!` });
});
Step 6: Start the Server
Finally, start the server:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Conclusion
With this setup, you now have a working authentication system using JWT in Express.js.
You can extend this by connecting to a database for persistent user storage and enhancing token expiration or refresh mechanisms.