Home >Web Front-end >JS Tutorial >Role-Based Authentication in MERN Stack: A Complete Guide

Role-Based Authentication in MERN Stack: A Complete Guide

Susan Sarandon
Susan SarandonOriginal
2025-01-10 22:39:42337browse

Role-Based Authentication in MERN Stack: A Complete Guide

Authentication is a crucial aspect of web applications, ensuring that only authorized users can access certain resources. Role-Based Authentication (RBAC) takes this a step further by assigning different permissions to users based on their roles.

In this post, we'll cover:
✅ What is Role-Based Authentication?
✅ Why Use Role-Based Authentication?
✅ How to Implement RBAC in a MERN Stack Application

What is Role-Based Authentication?
Role-Based Access Control (RBAC) is a security approach where users are assigned roles, and each role has specific permissions.

For example, in an e-commerce application:

Admin can add, edit, or delete products.
Seller can manage their own products.
Customer can only view and purchase products.
This ensures that users can only perform actions relevant to their roles.

Why Use Role-Based Authentication?
✔ Enhanced Security – Prevents unauthorized access to sensitive operations.
✔ Scalability – Easily add new roles and permissions as the system grows.
✔ Better User Management – Assign permissions without modifying code.

How to Implement RBAC in a MERN Stack Application?
1️⃣ Setting Up the User Model (MongoDB Mongoose)
In your models/user.model.js:

javascript
Copy code
const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
role: {
type: String,
enum: ["admin", "seller", "customer"],
default: "customer"
}
});

module.exports = mongoose.model("User", UserSchema);
? Here, each user has a role field, which determines their permissions.

2️⃣ Generating JWT Tokens for Authentication
In your controllers/auth.controller.js:

javascript
Copy code
const jwt = require("jsonwebtoken");
const User = require("../models/user.model");

const login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });

if (!user || user.password !== password) {
return res.status(401).json({ message: "Invalid credentials" });
}

const token = jwt.sign({ userId: user._id, role: user.role }, "SECRET_KEY", { expiresIn: "1h" });

res.json({ token, role: user.role });
};

module.exports = { login };
? This function generates a JWT token containing the user's role.

3️⃣ Creating Middleware to Restrict Access
In middlewares/auth.middleware.js:

javascript
Copy code
const jwt = require("jsonwebtoken");

const authenticate = (req, res, next) => {
const token = req.header("Authorization")?.split(" ")[1];

if (!token) return res.status(403).json({ message: "Access denied" });

try {
const decoded = jwt.verify(token, "SECRET_KEY");
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ message: "Invalid token" });
}
};

const authorize = (roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ message: "Forbidden" });
}
next();
};
};

module.exports = { authenticate, authorize };
? authenticate – Ensures only logged-in users can access routes.
? authorize – Restricts access based on roles.

4️⃣ Protecting Routes Based on User Roles
In routes/admin.routes.js:

javascript
Copy code
const express = require("express");
const { authenticate, authorize } = require("../middlewares/auth.middleware");

const router = express.Router();

router.get("/admin-dashboard", authenticate, authorize(["admin"]), (req, res) => {
res.json({ message: "Welcome to the Admin Dashboard" });
});

module.exports = router;
? Only users with the admin role can access /admin-dashboard.

5️⃣ Implementing Role-Based UI in React
In App.js (Frontend):

javascript
Copy code
import { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
const [role, setRole] = useState(null);

useEffect(() => {
const token = localStorage.getItem("token");
if (token) {
const decoded = JSON.parse(atob(token.split(".")[1]));
setRole(decoded.role);
}
}, []);

return (


Welcome to MERN Role-Based Authentication


{role === "admin" && Admin Dashboard}
{role === "seller" && Seller Dashboard}
{role === "customer" && Customer Dashboard}

);
};

export default App;
? The UI displays different dashboards based on the user's role.

Conclusion
Role-Based Authentication is an essential security measure in modern web applications. By implementing RBAC in MERN Stack, you can control user permissions efficiently.

? Next Steps:
? Add a role management panel for admins.
? Implement database encryption for passwords.
? Use Refresh Tokens for better security.

Want to learn more? Drop your questions in the comments! ?

The above is the detailed content of Role-Based Authentication in MERN Stack: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn