Back to 20 Concepts
authz-rbacIntermediate

OAuth 2.0 Scopes, Claims & Principle of Least Privilege

OAuth 2.0 scopes (e.g. read:profile, write:orders) limit the permissions granted to third-party applications. Resource servers inspect token scope claims before executing protected API operations.

Intuitive Mental Model

The Valet Parking Key: When you give your car to a valet, you hand them a valet key (Scope: drive_only) that starts the engine but cannot open the locked glovebox or trunk.

Architecture Blueprint & CodeProduction Standard
// Express Scope Verification Middleware:
function requireScope(requiredScope: string) {
  return (req: any, res: any, next: any) => {
    const userScopes: string[] = req.auth?.scope?.split(' ') || [];
    if (!userScopes.includes(requiredScope)) {
      return res.status(403).json({ error: 'Insufficient scope', required: requiredScope });
    }
    next();
  };
}

app.post('/api/orders', requireScope('write:orders'), createOrderHandler);

Key Architectural Takeaways

  • Least Privilege: Third-party apps request only the minimal permissions required for their specific function.
  • User Consent Gating: The authorization server presents the exact requested scope list to the user during login approval.
Common Architectural Pitfall

Requesting broad wildcard scopes (scope: admin:all) for simple client widgets, exposing users to severe over-permissioning risks.

Production Best Practice

Split permissions into fine-grained read and write scopes (read:reports, write:reports).