const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const secretKey = 'mySecretKey';
app.post('/login', (req, res) => {
const { username, password } = req.body;
// Authenticate the user (e.g., check credentials against a database)
const token = jwt.sign({ username }, secretKey);
res.json({ token });
});
app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
res.status(401).send('Unauthorized');
} else {
res.send(`Welcome back, ${decoded.username}!`);
}
});
});
app.listen(3000);