Create an express server that has an authorised endpoint using the JWT library.
Tue Apr 08 2025 00:08:39 GMT+0000 (Coordinated Universal Time)
Saved by
@p9876543
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = 3000;
const SECRET_KEY = 'secret';
app.use(express.json());
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'user' && password === '123') {
const token = jwt.sign({ username }, SECRET_KEY);
res.json({ token });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
function auth(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.get('/protected', auth, (req, res) => {
res.json({ message: 'Welcome!', user: req.user });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
npm init -y
npm install express jsonwebtoken body-parser
content_copyCOPY
Comments