Explore Library
Code QuizAdvanced

Reading JWT Claims Safely

Spot the flaw in an Express route that authorizes users based on a JWT role claim.

Codejavascript
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET;

function requireAdmin(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).send('No token');

  // Read the claims from the token
  const payload = jwt.decode(token);

  if (payload.role === 'admin') {
    req.user = payload;
    return next();
  }
  return res.status(403).send('Forbidden');
}

What is the security bug in this authorization middleware?