Skip to main content
Authorization controls what authenticated users are allowed to do. After verifyToken sets req.user, authorization middleware checks whether that user’s role permits the requested action. This page builds role middleware, ownership checks, and explains 401 vs 403.

What Is Authorization

Authorization decides what an authenticated user can do. Examples:
  • Only admin users can delete other users
  • Only the post author can edit their post
  • Only moderator and admin can approve content
Authorization always runs AFTER authentication. verifyToken sets req.user first, then checkRole reads req.user.role.

Roles in MySQL

The role column is defined as an ENUM in the users table:
The role is included in the JWT payload at login:
From then on, req.user.role is available in every middleware after verifyToken.

checkRole Middleware

Usage — chain verifyToken then checkRole:

Allowing Multiple Roles

Resource Ownership Check

A user should only edit their own posts, not other users’ posts:
Usage:

401 vs 403

Classic exam question. Know the exact difference.
Simple rule: 401 = “I don’t know who you are.” 403 = “I know who you are, but you can’t do this.”

Full Admin Route Example

RBAC vs ABAC

ABAC example: “User can edit a post only if they are the author AND the post is still in ‘draft’ status.” For most MySQL-backed APIs, RBAC is sufficient.

Key Terms

Common Mistakes

checkRole reads req.user.role. If verifyToken has not run yet, req.user is undefined and checkRole crashes. Always: verifyToken THEN checkRole.
No token = 401. Only return 403 when the identity is confirmed but the action is denied.
Always use db.query(sql, [req.params.id], …) with ? placeholders. Never concatenate req.params.id directly into the SQL string.