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
adminusers can delete other users - Only the post author can edit their post
- Only
moderatorandadmincan approve content
Authorization always runs AFTER authentication.
verifyToken sets req.user first, then checkRole reads req.user.role.Roles in MySQL
Therole column is defined as an ENUM in the users table:
req.user.role is available in every middleware after verifyToken.
checkRole Middleware
Allowing Multiple Roles
Resource Ownership Check
A user should only edit their own posts, not other users’ posts:401 vs 403
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
Checking roles before verifyToken
Checking roles before verifyToken
checkRole reads req.user.role. If verifyToken has not run yet, req.user is undefined and checkRole crashes. Always: verifyToken THEN checkRole.
Returning 403 when token is missing
Returning 403 when token is missing
No token = 401. Only return 403 when the identity is confirmed but the action is denied.
Not parameterizing the ownership query
Not parameterizing the ownership query
Always use db.query(sql, [req.params.id], …) with ? placeholders. Never concatenate req.params.id directly into the SQL string.