A production-ready authentication backend built with Node.js, Express, MongoDB implementing secure authentication using password hashing, JWT, cookies, validation, and Role-Based Access Control (RBAC).
- ✅ User Registration & Login
- ✅ Password Hashing (bcrypt)
- ✅ JWT Authentication (access token)
- ✅ JWT stored in HttpOnly Cookies
- ✅ Protected Routes Middleware
- ✅ Role-Based Access Control (RBAC)
- ✅ Permission-based Authorization Middleware
- ✅ Input Validation (express-validator)
- ✅ Environment Variables (.env)
- ✅ Clean Folder Structure (MVC pattern)
Register → password hashed → saved in DB
Login → JWT generated → stored in HttpOnly cookie
Client request → cookie sent automatically
Protect middleware → verify JWT → req.user created
Authorization middleware → check role/permission → allow or deny
AUTH_BACKEND
│
├── config
│ ├── db.js
│ └── roles.js
│
├── controller
│ └── authController.js
│
├── middleware
│ ├── protect.js
│ └── authorizationPermission.js
│
├── model
│ └── user.js
│
├── routes
│ └── authRoutes.js
│
├── .env
├── server.js
├── package.json
└── .gitignore
- Node.js
- Express.js
- MongoDB + Mongoose
- bcrypt
- jsonwebtoken
- cookie-parser
- crypto
- nodemailer
- express-validator
Passwords are hashed using bcrypt before storing in database.
JWT contains user id and role and is verified on every request.
JWT is stored in HttpOnly cookies to prevent XSS attacks.
Request validation prevents invalid or malicious input.
Access to routes depends on user role.
Defined in:
config/roles.js
Example:
USER
ADMIN
Roles are included inside JWT payload and used by authorization middleware.
- Reads JWT from cookies
- Verifies token
- Attaches decoded user to
req.user
- Checks user role/permission
- Blocks unauthorized access
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/auth/register | Register user |
| POST | /api/auth/login | Login user |
| POST | /api/auth/logout | Logout user |
router.get("/admin", protect, authorize("ADMIN"), controller)
Create .env
PORT=5000
MONGO_URI=your_mongodb_uri
JWT_SECRET=your_secret
NODE_ENV=development
git clone https://github.com/yourusername/AUTH_BACKEND.git
cd AUTH_BACKEND
npm install
Create .env file.
npm run dev
or
npm start
You can test using:
- Postman
- Thunder Client
- Frontend app
Cookies will be set automatically after login.
- Refresh token system
- Email verification
- Password reset
- Rate limiting
- Account lock on brute force
- Permission-based RBAC (advanced)
- OAuth login (Google/Github)
This project demonstrates:
- Stateless authentication architecture
- Middleware design patterns
- Secure cookie strategy
- RBAC implementation
- Production backend structure
Himanshu Singh Sengar MERN Stack Developer
Give it a ⭐ on GitHub.