Authorization and Protected Routes in Node.js
Authorization determines what an authenticated user is allowed to do. In Node.js applications, authorization is commonly implemented using middleware, roles, permissions, and protected API routes.
1. What Is Authorization?
Authorization is the process of deciding whether a user has permission to access a particular resource or perform a specific action.
For example, an Admin may manage all users, while a normal User may only view their own profile.
| Concept | Meaning | Example |
|---|---|---|
| Authentication | Verifies who the user is. | Checking email and password during login. |
| Authorization | Checks what the user can access. | Allowing only Admins to delete users. |
2. Why Do We Need Authorization?
- To prevent unauthorized access to sensitive resources.
- To restrict administrative operations to approved users.
- To protect user-specific information.
- To enforce business rules and permissions.
- To separate access for Admin, Manager, and User roles.
3. How Authorization Works
The client requests a protected API.
JWT middleware verifies the user's token.
The server checks the user's role or permission.
The request is allowed or rejected.
4. What Is Role-Based Authorization?
Role-Based Access Control (RBAC) assigns permissions according to a user's role. The application checks the role before allowing a restricted operation.
| Role | View Profile | Manage Users | Delete Users |
|---|---|---|---|
| Admin | Yes | Yes | Yes |
| Manager | Yes | Limited | No |
| User | Own profile | No | No |
The table is an example policy. Actual permissions depend on your application's business requirements.
5. Use the JWT Authentication Middleware
In the previous lesson, we created authenticateToken.
It verifies the JWT and adds the verified user ID to req.user.
Authorization middleware can run after that check.
const jwt = require("jsonwebtoken");
function authenticateToken(req, res, next) {
const authorization = req.headers.authorization;
if (!authorization || !authorization.startsWith("Bearer ")) {
return res.status(401).json({
message: "Authentication token is required."
});
}
const token = authorization.slice(7).trim();
if (!token) {
return res.status(401).json({
message: "Authentication token is required."
});
}
try {
const decoded = jwt.verify(
token,
process.env.JWT_SECRET,
{
issuer: process.env.JWT_ISSUER,
audience: process.env.JWT_AUDIENCE,
algorithms: ["HS256"]
}
);
if (typeof decoded.sub !== "string") {
return res.status(401).json({
message: "Invalid authentication token."
});
}
req.user = {
id: decoded.sub
};
next();
} catch (error) {
return res.status(401).json({
message: "Invalid or expired authentication token."
});
}
}
module.exports = authenticateToken;
6. Create Role-Based Authorization Middleware
Create a middleware that checks whether the authenticated user has an allowed role.
function authorizeRoles(...allowedRoles) {
return (req, res, next) => {
if (!req.user || !allowedRoles.includes(req.user.role)) {
return res.status(403).json({
message: "You do not have permission to access this resource."
});
}
next();
};
}
module.exports = authorizeRoles;
This middleware expects req.user.role to be populated from
a trusted source before it runs. We will load the current user's role
from the database in the next example.
7. Load the User Role from the Database
For sensitive operations, load the user's current role from the database after verifying the token. This means a role change in the database can take effect without trusting a role supplied by the client.
const db = require("./db");
async function loadUserRole(req, res, next) {
try {
const [users] = await db.execute(
"SELECT id, role FROM users WHERE id = ?",
[req.user.id]
);
if (users.length === 0) {
return res.status(401).json({
message: "User account not found."
});
}
req.user.role = users[0].role;
next();
} catch (error) {
console.error("Role lookup error:", error);
return res.status(500).json({
message: "An internal server error occurred."
});
}
}
module.exports = loadUserRole;
users table contains a role column.
Add it through a proper database migration if it does not exist.
Assign roles only through trusted, access-controlled server operations.
8. Create Protected Routes
We can now combine authentication, role loading, and authorization to protect an Admin-only endpoint.
require("dotenv").config();
const express = require("express");
const authenticateToken = require("./authMiddleware");
const loadUserRole = require("./loadUserRole");
const authorizeRoles = require("./roleMiddleware");
const app = express();
app.use(express.json());
// Any authenticated user can access this route.
app.get("/api/profile", authenticateToken, (req, res) => {
res.status(200).json({
message: "Profile endpoint accessed successfully.",
userId: req.user.id
});
});
// Only Admin users can access this route.
app.get(
"/api/admin/users",
authenticateToken,
loadUserRole,
authorizeRoles("Admin"),
(req, res) => {
res.status(200).json({
message: "Admin access granted."
});
}
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Middleware runs in order. First, the JWT is verified. Next, the user's current role is loaded. Finally, the role is checked before the endpoint runs.
9. Test Authorization in Postman
Test 1: Access the Profile
GET http://localhost:3000/api/profile
Add a valid JWT in Authorization → Bearer Token. An authenticated user should receive a successful response.
Test 2: Access the Admin Route as Admin
GET http://localhost:3000/api/admin/users
Expected response for a user whose database role is Admin:
{
"message": "Admin access granted."
}
Test 3: Access the Admin Route as a Normal User
Send the same request using a valid token for a user whose database role is User.
{
"message": "You do not have permission to access this resource."
}
The server returns 403 Forbidden because the user is authenticated
but does not have the required role.
10. Authentication vs Authorization Status Codes
| Status Code | Meaning |
|---|---|
| 200 OK | The request succeeded. |
| 401 Unauthorized | The request has missing or invalid authentication. |
| 403 Forbidden | The user is authenticated but lacks permission. |
| 500 Internal Server Error | An unexpected server-side error occurred. |
11. Authorization Best Practices
- Verify authentication before checking permissions.
- Never trust a role sent directly by the client.
- Use the database or another trusted source for sensitive permissions.
- Apply authorization checks to every protected endpoint.
- Restrict users to their own records unless they have broader permission.
- Use the principle of least privilege.
- Return 401 for authentication failures and 403 for insufficient permissions.
- Test both allowed and denied access scenarios.
Important Points to Remember
- Authentication verifies the user's identity.
- Authorization checks the user's permissions.
- Role-based authorization is commonly called RBAC.
- Authentication middleware can populate
req.user. - Authorization middleware checks roles or permissions.
- Use 401 for invalid authentication and 403 for denied access.
- Never allow users to assign themselves privileged roles.
Summary
Authorization controls which actions an authenticated user can perform. By combining JWT authentication, trusted role lookup, and role-based middleware, a Node.js application can protect sensitive APIs and restrict access according to business requirements.