DEV Community

niuniu
niuniu

Posted on

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, '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' });
  }
};
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

security #jwt #tips

Top comments (0)