Quick Tip: JWT Authentication Basics
Quick Tip JWT authentication basics: // Generate JWT const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: 1 }, 'secret', { expiresIn: '1h' }); // Verify JWT const decoded = jwt.verify(token, 'secre
Quick Tip
JWT authentication basics:
// Generate JWT
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secret', { expiresIn: '1h' });
// Verify JWT
const decoded = jwt.verify(token, 'secret');
// Middleware
const auth = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token' });
try {
const decoded = jwt.verify(token, 'secret');
req.userId = decoded.userId;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};
Powered by MonkeyCode: https://monkeycode-ai.net/
security #jwt #tips
📰 Read the original article on Dev.to Security
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.