In this tutorial, we’ll implement JSON Web Token (JWT) authentication in a Node.js application using Express and the `jsonwebtoken` package.
Node.js JWT Authentication
1. Setting Up the Project
First, create a new project and install necessary packages:
mkdir jwt-app
cd jwt-app
npm init -y
npm install express jsonwebtoken body-parser
This initializes your project and installs Express, jsonwebtoken, and body-parser.
2. Create JWT Token
In `app.js`, create the routes to handle authentication and generate JWT tokens:
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
app.use(bodyParser.json());
// Secret key for signing the JWT
const secretKey = 'your-secret-key';
// Mock user data
const user = { id: 1, username: 'user', password: 'password' };
// Authenticate and generate JWT
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === user.username && password === user.password) {
const token = jwt.sign({ id: user.id, username: user.username }, secretKey, { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).send('Invalid credentials');
}
});
// Protected route (requires JWT)
app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('Token is required');
jwt.verify(token, secretKey, (err, decoded) => {
if (err) return res.status(403).send('Invalid token');
res.json({ message: 'Protected content', user: decoded });
});
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
This code provides a login route that generates a JWT when correct credentials are provided and a protected route that requires the JWT for access.
3. Testing the Application
You can test the application using Postman:
- Send a POST request to
/login
with the correct username and password to receive a JWT token. - Send a GET request to
/protected
with the JWT token in theAuthorization
header.
4. Conclusion
By following this tutorial, you’ve implemented JWT authentication in your Node.js application, allowing users to securely access protected resources.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.