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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter