Production-Grade Authentication & Authorization Service
A comprehensive, enterprise-ready authentication and authorization service built with Node.js, featuring RBAC, OAuth integration, advanced security hardening, and horizontal scalability.
- JWT-based authentication with access + refresh tokens
- Token rotation for enhanced security
- Secure cookie handling with httpOnly and sameSite flags
- Password hashing with bcrypt (cost factor: 12)
- Account lockout after failed login attempts
- OAuth 2.0 integration (Google, GitHub)
- Role-Based Access Control (RBAC)
- Attribute-Based Access Control (ABAC) support
- Permission matrix system
- Middleware-driven authorization checks
- Policy-driven logic (not hardcoded)
- Rate limiting on all auth endpoints
- CSRF protection for state-changing operations
- Secure headers via Helmet.js
- Input validation with Joi schemas
- Brute-force detection and prevention
- MongoDB injection protection
- XSS protection
- Audit logging for all auth events
- Correlation IDs for request tracing
- Security alerts for suspicious activities
- Metrics tracking (failed logins, token refresh rates)
- Structured logging with Winston
- Unit tests for all auth flows
- Integration tests for API endpoints
- Security tests for attack scenarios
- Abuse scenario coverage
- Dockerized service
- Environment separation (dev, staging, prod)
- Secrets management best practices
- Horizontal scaling ready (stateless architecture)
secure-auth-platform/
βββ src/
β βββ lib/
β β βββ security/ # Security middleware & utilities
β β βββ rateLimiter/ # Rate limiting configuration
β β βββ tokenManager/ # Token generation & validation
β β βββ auditLogger/ # Security event logging
β β βββ oauth/ # OAuth providers
β βββ models/
β β βββ User/ # User model with security features
β β βββ RefreshToken/ # Refresh token storage
β β βββ AuditLog/ # Security audit logs
β βββ routes/
β β βββ auth.js # Authentication routes
β β βββ oauth.js # OAuth routes
β β βββ user.js # User management routes
β βββ services/
β β βββ auth/ # Authentication business logic
β β βββ token/ # Token management
β β βββ oauth/ # OAuth integration
β βββ middleware/
β β βββ rbac.js # RBAC middleware
β β βββ abac.js # ABAC middleware
β β βββ bruteforce.js # Brute-force protection
β βββ validations/ # Joi validation schemas
βββ tests/
β βββ unit/ # Unit tests
β βββ integration/ # Integration tests
β βββ security/ # Security & abuse tests
βββ docs/
β βββ auth-flow.md # Authentication flow diagrams
β βββ threat-model.md # Security threat analysis
β βββ token-strategy.md # Token management strategy
β βββ rate-limiting.md # Rate limiting configuration
β βββ rbac-permissions.md # Permission matrix
β βββ deployment.md # Deployment guide
βββ infra/
β βββ Dockerfile # Container configuration
β βββ docker-compose.yml # Multi-service setup
βββ config/ # Configuration files
βββ README.md
- Node.js >= 14.x
- MongoDB >= 4.x
- Redis >= 6.x (for token blacklisting)
# Clone the repository
git clone https://github.com/tapas100/node-auth-app.git
cd node-auth-app
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Edit .env with your configuration
# Start MongoDB
sudo service mongod start
# Start Redis (for token management)
redis-server
# Start the application
npm run dev# Build the image
npm run docker:build
# Run the container
npm run docker:runWhy we use refresh tokens:
- Security: Short-lived access tokens limit exposure window
- Revocation: Can invalidate refresh tokens without affecting active sessions
- Scalability: Stateless access tokens reduce database lookups
- User Experience: Seamless re-authentication without login
Flow:
1. User logs in β Server returns access token (15min) + refresh token (7d)
2. Client stores refresh token securely (httpOnly cookie)
3. Client uses access token for API requests
4. Access token expires β Client sends refresh token
5. Server validates refresh token β Issues new access + refresh token pair
6. Old refresh token is rotated (invalidated)
See docs/auth-flow.md for detailed diagrams.
Default Roles:
admin- Full system accessmoderator- Content management + user moderationeditor- Content creation and editinguser- Basic authenticated accessguest- Read-only access
Permission Matrix:
| Role | manage_users | publish_content | edit_content | read_content | delete_content |
|---|---|---|---|---|---|
| admin | β | β | β | β | β |
| moderator | β | β | β | β | β |
| editor | β | β | β | β | β |
| user | β | β | β | β | β |
| guest | β | β | β | β | β |
See docs/rbac-permissions.md for the complete permission matrix.
// Login endpoint: 5 attempts per 15 minutes per IP
// Token refresh: 10 attempts per 15 minutes per IP
// Registration: 3 attempts per hour per IPSee docs/rate-limiting.md for configuration details.
- Account lockout after 5 failed attempts
- Progressive delays (exponential backoff)
- IP-based tracking
- CAPTCHA requirement after 3 failed attempts
- Minimum 8 characters
- Must contain: uppercase, lowercase, number, special character
- Cannot contain common passwords (dictionary check)
- Cannot reuse last 5 passwords
- Hashed with bcrypt (cost factor: 12)
POST /api/v1/auth/register - Register new user
POST /api/v1/auth/login - Login with credentials
POST /api/v1/auth/logout - Logout (invalidate tokens)
POST /api/v1/auth/refresh - Refresh access token
POST /api/v1/auth/forgot-password - Request password reset
POST /api/v1/auth/reset-password - Reset password with token
GET /api/v1/oauth/google - Initiate Google OAuth
GET /api/v1/oauth/google/callback - Google OAuth callback
GET /api/v1/oauth/github - Initiate GitHub OAuth
GET /api/v1/oauth/github/callback - GitHub OAuth callback
GET /api/v1/users/me - Get current user profile
PUT /api/v1/users/me - Update current user
DELETE /api/v1/users/me - Delete account
GET /api/v1/users/:id - Get user by ID (admin only)
PUT /api/v1/users/:id/roles - Update user roles (admin only)
Full API Documentation: Postman Collection
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run security tests only
npm run test:security
# View coverage report
npm test -- --coverage- Unit Tests: Authentication logic, token validation, password hashing
- Integration Tests: API endpoints, middleware chains, database operations
- Security Tests:
- Token replay attacks
- Expired token handling
- Concurrent login scenarios
- Brute-force attempts
- SQL/NoSQL injection attempts
- XSS attempts
# Server
PORT=3000
NODE_ENV=production
# Database
MONGODB_URI=mongodb://localhost:27017/auth-platform
REDIS_URL=redis://localhost:6379
# JWT
JWT_SECRET=<your-super-secret-key>
JWT_ACCESS_EXPIRATION=15m
JWT_REFRESH_EXPIRATION=7d
# OAuth
GOOGLE_CLIENT_ID=<your-google-client-id>
GOOGLE_CLIENT_SECRET=<your-google-client-secret>
GITHUB_CLIENT_ID=<your-github-client-id>
GITHUB_CLIENT_SECRET=<your-github-client-secret>
# Security
BCRYPT_ROUNDS=12
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION=900000 # 15 minutes in ms
RATE_LIMIT_WINDOW=900000 # 15 minutes in msAll security events are logged with correlation IDs for tracing. See docs/security-logging.md for details.
Decision: Use JWT for access tokens (stateless)
Why:
- Horizontal scaling without session storage
- Reduced database lookups
- Better performance under load
Trade-off:
- Cannot immediately revoke access tokens
- Mitigated with short expiration (15 min) + refresh token rotation
Decision: Rotate refresh tokens on every use
Why:
- Prevents token replay attacks
- Limits damage from token theft
- Detects concurrent token usage
Trade-off:
- Slightly more complex client logic
- Additional database writes
Decision: Use Redis for revoked token tracking
Why:
- Fast in-memory lookups
- TTL support (auto-cleanup)
- Scales horizontally
Trade-off:
- Additional infrastructure dependency
- Requires Redis availability
100K+ users:
- Add Redis cluster for distributed rate limiting
- Implement CDN for static assets
- Add read replicas for MongoDB
1M+ users:
- Microservices architecture (separate auth service)
- Event-driven architecture with message queues
- Distributed tracing (Jaeger/OpenTelemetry)
- Multi-region deployment
10M+ users:
- Dedicated identity provider (Keycloak/Auth0)
- Geographically distributed databases
- Edge authentication (Cloudflare Workers)
- Advanced fraud detection with ML
See docs/threat-model.md for comprehensive threat analysis.
ISC License
Tapas Mahanta - @tapas100