Implementing Role-Based Access Control in MEAN Stack
Implementing Role-Based Access Control in MEAN Stack
Implementing Role-Based Access Control (RBAC) in a MEAN Stack (MongoDB, Express.js, Angular, Node.js) application involves assigning specific roles to users and controlling access to resources based on those roles. Here's a step-by-step guide to implementing RBAC in a typical MEAN application:
๐ Role-Based Access Control in MEAN Stack
1. Define User Roles
First, decide the roles needed for your application. For example:
admin
editor
viewer
2. Backend (Node.js + Express.js + MongoDB)
๐ A. User Schema (models/User.js)
js
Copy
Edit
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
username: String,
password: String,
role: {
type: String,
enum: ['admin', 'editor', 'viewer'],
default: 'viewer'
}
});
module.exports = mongoose.model('User', UserSchema);
๐ B. Middleware to Check Roles (middleware/auth.js)
js
Copy
Edit
// Check if user is authenticated and has a required role
function authorizeRoles(...allowedRoles) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({ message: 'Unauthorized' });
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({ message: 'Forbidden: Access denied' });
}
next();
};
}
module.exports = {
authorizeRoles
};
๐ C. Authentication Middleware (middleware/jwtAuth.js)
Assumes you use JWT for authentication.
js
Copy
Edit
const jwt = require('jsonwebtoken');
const User = require('../models/User');
async function authenticateJWT(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'No token provided' });
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.userId).select('-password');
next();
} catch (err) {
res.status(403).json({ message: 'Invalid token' });
}
}
module.exports = { authenticateJWT };
๐ D. Secured Routes Example (routes/admin.js)
js
Copy
Edit
const express = require('express');
const router = express.Router();
const { authenticateJWT } = require('../middleware/jwtAuth');
const { authorizeRoles } = require('../middleware/auth');
router.get('/dashboard', authenticateJWT, authorizeRoles('admin'), (req, res) => {
res.json({ message: 'Welcome to the admin dashboard' });
});
module.exports = router;
3. Frontend (Angular)
๐ A. User Role Handling (e.g., AuthService)
ts
Copy
Edit
getUserRole(): string {
const user = JSON.parse(localStorage.getItem('user')!);
return user?.role;
}
isAdmin(): boolean {
return this.getUserRole() === 'admin';
}
๐ B. Role-Based Guard (auth.guard.ts)
ts
Copy
Edit
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AdminGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isAdmin()) {
return true;
}
this.router.navigate(['/unauthorized']);
return false;
}
}
๐ C. Angular Routes with Role Guard
ts
Copy
Edit
const routes: Routes = [
{ path: 'admin', component: AdminComponent, canActivate: [AdminGuard] },
{ path: 'unauthorized', component: UnauthorizedComponent }
];
4. Security Tips
Always validate roles on the server – never trust client-side role enforcement.
Use HTTPS to protect tokens.
Store only non-sensitive user info in localStorage/sessionStorage.
Keep user roles in JWT or use session-based auth if preferred.
Learn MEAN Stack Course
Read More
Using Angular Services to Interact with MongoDB MEAN
Form Validation in Angular with Express API Integration MEAN
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment