{"id":24427399,"url":"https://github.com/siteitsolutions/nestjs-auth-microservice","last_synced_at":"2026-04-19T05:37:02.528Z","repository":{"id":271170444,"uuid":"912594061","full_name":"SiteitSolutions/NestJS-Auth-Microservice","owner":"SiteitSolutions","description":"NestJS - HTTP Based Auth Microservice","archived":false,"fork":false,"pushed_at":"2025-01-06T07:42:03.000Z","size":131,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-01-20T12:11:29.456Z","etag":null,"topics":["authentication","authorization","microservice","nestjs","open-source","opensource","passportjs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SiteitSolutions.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-06T01:49:20.000Z","updated_at":"2025-01-06T07:42:06.000Z","dependencies_parsed_at":null,"dependency_job_id":"b623b815-d4bb-4364-b05f-985acdc453ad","html_url":"https://github.com/SiteitSolutions/NestJS-Auth-Microservice","commit_stats":null,"previous_names":["siteitsolutions/nestjs-auth-microservice"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SiteitSolutions%2FNestJS-Auth-Microservice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SiteitSolutions%2FNestJS-Auth-Microservice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SiteitSolutions%2FNestJS-Auth-Microservice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SiteitSolutions%2FNestJS-Auth-Microservice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SiteitSolutions","download_url":"https://codeload.github.com/SiteitSolutions/NestJS-Auth-Microservice/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243447517,"owners_count":20292448,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","authorization","microservice","nestjs","open-source","opensource","passportjs"],"created_at":"2025-01-20T12:10:31.778Z","updated_at":"2026-04-19T05:37:02.480Z","avatar_url":"https://github.com/SiteitSolutions.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NestJS Auth Microservice\n\nAn **enterprise-grade authentication and authorization microservice** built with **NestJS**, **PassportJS**, and **MongoDB**. This microservice provides comprehensive user authentication, session management, role-based access control (RBAC), and advanced security features.\n\n---\n\n## 🚀 **Key Features**\n\n### Authentication \u0026 Authorization\n- **Local authentication** with email/password\n- **JWT-based access and refresh tokens** with automatic rotation\n- **Session management** with device tracking and multi-device support\n- **Role-Based Access Control (RBAC)** with decorators\n- **Account security** with lockout protection and login attempt tracking\n\n### Security Features\n- **Advanced session validation** - tokens are invalidated when sessions are revoked\n- **Token blacklisting** with Redis for instant invalidation\n- **Refresh token rotation** for enhanced security\n- **Rate limiting** and DDoS protection\n- **Security headers** with Helmet.js\n- **Input validation** and sanitization\n- **Password complexity** requirements with bcrypt hashing\n\n### Session Management\n- **Multi-device session tracking** with device information\n- **Session revocation** - logout from all devices or specific sessions\n- **Session analytics** - last used timestamps and device details\n- **Automatic cleanup** of expired sessions\n\n### Developer Experience\n- **Comprehensive Swagger documentation** (development only)\n- **TypeScript interfaces** for type safety\n- **Detailed logging** with Winston\n- **Docker support** with multi-service setup\n- **Environment-based configuration**\n\n---\n\n## 📚 **Documentation**\n\n- **[Security Guide](docs/SECURITY.md)** - Security features and best practices\n- **[Session Management](docs/SESSION_MANAGEMENT.md)** - Session handling and device management\n- **[API Consumer Guide](docs/API_CONSUMER_GUIDE.md)** - How to integrate with other services\n- **[Orchestration Usage](docs/ORCHESTRATION_USAGE_GUIDE.md)** - Using with orchestration APIs\n- **[Practical Examples](docs/PRACTICAL_EXAMPLES.md)** - Real-world usage examples\n\n---\n\n## 🛠️ **Technologies**\n\n- **NestJS 10+** - Modern Node.js framework\n- **PassportJS** - Authentication middleware\n- **JWT** - Secure token-based authentication\n- **MongoDB** - Document database with Mongoose ODM\n- **Redis** - Caching and session management\n- **Winston** - Structured logging\n- **Helmet** - Security headers\n- **class-validator** - Input validation\n\n---\n\n## 🚦 **Getting Started**\n\n### **Prerequisites**\n\n- [Node.js](https://nodejs.org/) v18+\n- [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/)\n- [Git](https://git-scm.com/)\n\n### **Quick Start**\n\n```bash\n# 1. Clone the repository\ngit clone \u003crepository-url\u003e\ncd nestjs-auth-microservice\n\n# 2. Copy environment template\ncp .env.example .env\n\n# 3. Edit environment variables (see below)\nnano .env\n\n# 4. Start all services with Docker\ndocker-compose up -d --build\n\n# 5. Verify services are running\ncurl http://localhost:3000/auth/health\n```\n\nThe microservice will be available at `http://localhost:3000` with:\n- **API Documentation**: `http://localhost:3000/api` (development only)\n- **MongoDB**: `localhost:27017`\n- **Redis**: `localhost:6379`\n\n---\n\n## ⚙️ **Environment Configuration**\n\nCreate a `.env` file based on `.env.example`:\n\n```bash\n# Database Configuration\nMONGO_URI=mongodb://root:password@localhost:27017/nestdb?authSource=admin\n\n# Redis Configuration (for caching and token blacklisting)\nREDIS_HOST=localhost\nREDIS_PORT=6379\nREDIS_TTL=900000  # 15 minutes in milliseconds\n\n# JWT Configuration - CHANGE THESE IN PRODUCTION!\nJWT_SECRET=your-super-secret-jwt-key-here-make-it-long-and-random\nREFRESH_TOKEN_SECRET=your-super-secret-refresh-token-key-here-make-it-different-from-jwt\n\n# Application Configuration\nPORT=3000\nNODE_ENV=development\n\n# Security Configuration\nBCRYPT_ROUNDS=12\nMAX_LOGIN_ATTEMPTS=5\nLOCKOUT_TIME=900000  # 15 minutes in milliseconds\n\n# Rate Limiting\nRATE_LIMIT_TTL=60000  # 1 minute\nRATE_LIMIT_MAX=100    # requests per minute\n\n# CORS Configuration\nALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001\n\n# Session Security\nREQUIRE_SESSION_ID=false  # Set to true for stricter session validation\n```\n\n---\n\n## 🔌 **API Endpoints**\n\n### Authentication Endpoints\n\n| Method | Endpoint | Description | Rate Limit |\n|--------|----------|-------------|------------|\n| `POST` | `/auth/login` | User login with email/password | 3/min |\n| `POST` | `/auth/register` | Create new user account | 5/min |\n| `POST` | `/auth/logout` | Logout current session | - |\n| `POST` | `/auth/refresh` | Refresh access token | - |\n| `GET` | `/auth/profile` | Get current user profile | - |\n\n### Session Management Endpoints\n\n| Method | Endpoint | Description | Auth Required |\n|--------|----------|-------------|---------------|\n| `GET` | `/auth/sessions` | List all user sessions | ✅ |\n| `POST` | `/auth/logout-all` | Logout from all devices | ✅ |\n| `POST` | `/auth/logout-others` | Logout from other devices | ✅ |\n| `POST` | `/auth/revoke-session` | Revoke specific session | ✅ |\n\n### User Management Endpoints\n\n| Method | Endpoint | Description | Auth Required |\n|--------|----------|-------------|---------------|\n| `PATCH` | `/users/:id` | Update user profile | ✅ |\n| `DELETE` | `/users/:id` | Soft delete user | ✅ (Admin) |\n\n---\n\n## 📖 **Usage Examples**\n\n### **User Registration**\n\n```bash\ncurl -X POST http://localhost:3000/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"user@example.com\",\n    \"password\": \"SecurePass123!\",\n    \"givenName\": \"John\",\n    \"familyName\": \"Doe\"\n  }'\n```\n\n**Response:**\n```json\n{\n  \"_id\": \"65a1b2c3d4e5f6789abc0123\",\n  \"email\": \"user@example.com\",\n  \"givenName\": \"John\",\n  \"familyName\": \"Doe\",\n  \"roles\": [\"USER\"],\n  \"isActive\": true,\n  \"createdAt\": \"2023-12-01T10:30:00.000Z\"\n}\n```\n\n### **User Login with Device Tracking**\n\n```bash\ncurl -X POST http://localhost:3000/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -H \"X-Device-ID: mobile-app-v1.0\" \\\n  -H \"User-Agent: MyApp/1.0 (iOS 15.0; iPhone 13)\" \\\n  -d '{\n    \"email\": \"user@example.com\",\n    \"password\": \"SecurePass123!\"\n  }'\n```\n\n**Response:**\n```json\n{\n  \"accessToken\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n  \"refreshToken\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n}\n```\n\n### **Access Protected Resource**\n\n```bash\ncurl -X GET http://localhost:3000/auth/profile \\\n  -H \"Authorization: Bearer YOUR_ACCESS_TOKEN\"\n```\n\n### **Session Management**\n\n```bash\n# Get all active sessions\ncurl -X GET http://localhost:3000/auth/sessions \\\n  -H \"Authorization: Bearer YOUR_ACCESS_TOKEN\"\n\n# Logout from all devices\ncurl -X POST http://localhost:3000/auth/logout-all \\\n  -H \"Authorization: Bearer YOUR_ACCESS_TOKEN\"\n\n# Logout from other devices (keep current session)\ncurl -X POST http://localhost:3000/auth/logout-others \\\n  -H \"Authorization: Bearer YOUR_ACCESS_TOKEN\"\n```\n\n### **Token Refresh with Rotation**\n\n```bash\ncurl -X POST http://localhost:3000/auth/refresh \\\n  -H \"Authorization: Bearer YOUR_REFRESH_TOKEN\"\n```\n\n**Response:**\n```json\n{\n  \"accessToken\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n  \"refreshToken\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"\n}\n```\n\n---\n\n## 🔒 **Security Features**\n\n### **Rate Limiting**\n- Login attempts: **3 per minute**\n- Registration: **5 per minute**\n- Global API: **100 requests per minute**\n\n### **Account Protection**\n- Account lockout after **5 failed attempts**\n- Lockout duration: **15 minutes**\n- Progressive lockout for repeat offenders\n\n### **Session Security**\n- Automatic session validation on each request\n- Session revocation enforcement\n- Device tracking and management\n- Refresh token rotation\n\n### **JWT Security**\n- Separate secrets for access and refresh tokens\n- Token blacklisting with Redis\n- Short-lived access tokens (30 minutes)\n- Long-lived refresh tokens (7 days)\n\n---\n\n## 📊 **API Documentation**\n\n### **Swagger UI** (Development Only)\n- **URL**: `http://localhost:3000/api`\n- **Features**: Interactive API testing, request/response schemas, authentication\n\n### **Production Documentation**\n- Swagger is automatically disabled in production\n- Use this README and docs folder for production reference\n\n---\n\n## 🛡️ **Role-Based Access Control (RBAC)**\n\n### **Available Roles**\n- `USER` - Standard user permissions\n- `MODERATOR` - Elevated permissions for content management\n- `ADMIN` - Full system access\n\n### **Using Roles in Controllers**\n\n```typescript\nimport { Roles } from './decorators/role.decorator';\nimport { UserRole } from './enums/user-role.enum';\n\n@Patch(':id')\n@UseGuards(JwtAuthGuard, RolesGuard)\n@Roles(UserRole.ADMIN)\nasync updateUser(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {\n  return this.usersService.updateUser(id, updateUserDto);\n}\n```\n\n---\n\n## 🚀 **Production Deployment**\n\n### **Environment Variables for Production**\n\n```bash\nNODE_ENV=production\nREQUIRE_SESSION_ID=true  # Stricter session validation\nLOG_LEVEL=warn          # Reduce log verbosity\n```\n\n### **Security Checklist**\n- ✅ Change all default JWT secrets\n- ✅ Use strong database passwords\n- ✅ Configure Redis with authentication\n- ✅ Set up proper CORS origins\n- ✅ Enable stricter session validation\n- ✅ Use HTTPS in production\n- ✅ Configure proper logging levels\n\n---\n\n## 🤝 **Contributing**\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n---\n\n## 📄 **License**\n\nThis project is licensed under the MIT License. See `LICENSE` for details.\n\n---\n\n## 🆘 **Support**\n\n- **Documentation**: Check the `docs/` folder for detailed guides\n- **Issues**: Open an issue on GitHub\n- **Security**: Report security issues privately\n\nBuilt with ❤️ using NestJS, MongoDB, and Redis.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsiteitsolutions%2Fnestjs-auth-microservice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsiteitsolutions%2Fnestjs-auth-microservice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsiteitsolutions%2Fnestjs-auth-microservice/lists"}