To secure role-based access, you need to handle it both on the frontend (UI) and backend (API). Frontend restriction improves UX, backend enforcement ensures security.
🔹 1. Backend Security (Critical)
Steps:
- Define Roles: e.g.,
ADMINandUSER - Assign Roles to Users in your database during signup or via admin panel.
- Use Middleware to Protect Routes:
// Example Express.js middleware
function authorizeRoles(...allowedRoles) {
return (req, res, next) => {
const userRole = req.user.role; // assume role is decoded from JWT
if (!allowedRoles.includes(userRole)) {
return res.status(403).json({ message: "Access denied" });
}
next();
};
}
// Routes
app.get("/users", authorizeRoles("ADMIN", "USER"), (req, res) => {
res.send("User list");
});
app.delete("/users/:id", authorizeRoles("ADMIN"), (req, res) => {
res.send("User deleted");
});
- Use JWT or Session to identify the user and store their role in the token payload.
- Never rely only on frontend checks; backend is the true gatekeeper.
🔹 2. Frontend Security (UX)
- Show/Hide UI elements based on the user role.
- Example in React:
const userRole = currentUser.role; // fetched from context or decoded JWT
return (
<div>
<h1>User List</h1>
{userRole === "ADMIN" && <button>Edit</button>}
{userRole === "ADMIN" && <button>Delete</button>}
</div>
);
- Optional: Redirect unauthorized users if they try to access restricted routes:
if (userRole !== "ADMIN") {
navigate("/unauthorized");
}
🔹 3. Key Points
- Frontend: Improves user experience (hiding buttons, redirecting).
- Backend: Enforces true security (route protection, role validation).
- JWT/Session: Include role information to check permissions.
- Principle of Least Privilege: Give users only the access they need.
- Audit & Logging: Log critical actions like delete/edit for traceability.
✅ Summary:
- Backend is the authority: always check roles server-side.
- Frontend is convenience: hide or disable options for unauthorized users.
- Use middleware, JWT, and proper route protection to secure APIs.
I can also provide a diagram showing frontend + backend role enforcement flow if you want a visual explanation. Do you want me to do that?