This project demonstrates how to implement JWT authentication using the jsonwebtoken library.
- dotenv
- express
- jsonwebtoken
The project uses the following steps to implement JWT authentication:
- The user makes a login POST request.
- The server authenticates the user and generates a token.
- The server returns the token to the user.
- The user stores the token in their browser or on the server.
- The user makes a GET request to the
/posts
endpoint. - The server verifies the token and returns the posts that the user is authorized to see.
const express = require('express');
const app = express();
const jwt = require('jsonwebtoken');
app.use(express.json());
// Create a list of posts
const posts = [
{
"username": "ishak",
"title": "post 1",
},
{
"username": "moad",
"title": "post 2",
},
];
// Authenticate user
app.post('/login', (req, res) => {
const username = req.body.username;
const user = { "name": username };
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
return res.json({ "accessToken": accessToken });
});
// Verify token
app.get('/posts', authenticateToken, (req, res) => {
res.json(posts.filter((post) => post.username === req.user.name));
});
// Middleware to verify token
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader.split(' ')[1];
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
}
app.listen(3000);