JSON Web Token (JWT) is a compact, URL-safe means of representing claims between two parties. JWTs can be used for authentication and authorization purposes in web applications. In a Node.js application, you can implement JWT authentication using libraries like jsonwebtoken
and express
. Here's a step-by-step guide:
Install Dependencies: Install the necessary npm packages using the following commands:
bashnpm install express jsonwebtoken
Create an Express Application:
Create a new file (e.g., app.js
), and set up a basic Express application.
javascriptconst express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Generate JWT Tokens:
Create a utility function to generate and sign JWT tokens. You can use the jsonwebtoken
library for this purpose.
javascriptconst jwt = require('jsonwebtoken');
function generateToken(user) {
const payload = {
userId: user.id,
username: user.username,
};
const options = {
expiresIn: '1h', // Token expiration time
};
return jwt.sign(payload, 'your-secret-key', options);
}
Implement User Authentication: Create a route for user authentication. For simplicity, let's assume you have a hardcoded user object.
javascriptconst users = [
{ id: 1, username: 'john', password: 'password123' },
];
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find((u) => u.username === username && u.password === password);
if (user) {
const token = generateToken(user);
res.json({ token });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
Protect Routes with JWT: Create a middleware to protect routes that require authentication. This middleware verifies the JWT token.
javascriptfunction authenticateToken(req, res, next) {
const token = req.header('Authorization');
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
jwt.verify(token, 'your-secret-key', (err, user) => {
if (err) {
return res.status(403).json({ message: 'Forbidden' });
}
req.user = user;
next();
});
}
Use JWT Middleware:
Apply the authenticateToken
middleware to the routes that require authentication.
javascriptapp.get('/protected-route', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected route', user: req.user });
});
Now, when a user successfully logs in and receives a JWT token, they can use that token to access protected routes. The authenticateToken
middleware will verify the token before granting access to the protected resource.