Explore Library
Code Quiz

Role-Based Access from JWT Claims

Spot the bug in an Express middleware that authorizes users based on OIDC role claims.

Codejavascript
const jwt = require('jsonwebtoken');

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

    const decoded = jwt.verify(token, PUBLIC_KEY, { algorithms: ['RS256'] });

    // roles claim is an array, e.g. { roles: ['user', 'admin'] }
    if (decoded.roles === role) {
      return next();
    }
    return res.status(403).send('Forbidden');
  };
}

app.get('/admin', requireRole('admin'), handler);

What is the bug in this role-based authorization check?