{"id":42107956,"url":"https://github.com/tulbadex/nestjs-auth-api-key-system","last_synced_at":"2026-01-26T13:22:27.137Z","repository":{"id":328012034,"uuid":"1111737796","full_name":"tulbadex/nestjs-auth-api-key-system","owner":"tulbadex","description":"A NestJS authentication system supporting both JWT tokens for users and API keys for service-to-service access","archived":false,"fork":false,"pushed_at":"2025-12-10T17:39:48.000Z","size":314,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-11T03:50:31.865Z","etag":null,"topics":["api-keys","authentication","jwt","nestjs","postgresql","rest-api","service-to-service","typescript"],"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/tulbadex.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-07T14:45:15.000Z","updated_at":"2025-12-10T17:39:48.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/tulbadex/nestjs-auth-api-key-system","commit_stats":null,"previous_names":["tulbadex/nestjs-auth-api-key-system"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/tulbadex/nestjs-auth-api-key-system","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tulbadex%2Fnestjs-auth-api-key-system","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tulbadex%2Fnestjs-auth-api-key-system/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tulbadex%2Fnestjs-auth-api-key-system/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tulbadex%2Fnestjs-auth-api-key-system/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tulbadex","download_url":"https://codeload.github.com/tulbadex/nestjs-auth-api-key-system/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tulbadex%2Fnestjs-auth-api-key-system/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28779338,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-26T11:46:04.308Z","status":"ssl_error","status_checked_at":"2026-01-26T11:46:02.664Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["api-keys","authentication","jwt","nestjs","postgresql","rest-api","service-to-service","typescript"],"created_at":"2026-01-26T13:22:26.634Z","updated_at":"2026-01-26T13:22:27.131Z","avatar_url":"https://github.com/tulbadex.png","language":"TypeScript","readme":"# Task 3: Mini Authentication + API Key System\n\nA complete NestJS backend service that supports:\n- User authentication via JWT (signup/login)\n- Service-to-Service access via API keys\n- Flexible authentication middleware (accepts both JWT and API keys)\n- Protected routes based on access type\n\n## Features\n\n### User Authentication (JWT)\n- `POST /auth/signup` - Register new user\n- `POST /auth/login` - Login user\n- `POST /auth/logout` - Logout user (requires JWT)\n\n### API Key Management\n- `POST /keys/create` - Generate API keys (requires JWT)\n- `GET /keys` - List all API keys (requires JWT)\n- `DELETE /keys/:id` - Revoke API key (requires JWT)\n\n### Protected Routes\n- `GET /protected/user-only` - Accessible only with JWT Bearer token\n- `GET /protected/service-only` - Accessible only with API key\n- `GET /protected/flexible` - Accessible with both JWT and API key\n\n### Key Features\n- JWT token generation with refresh tokens\n- API key generation with expiration support\n- API key revocation\n- Last used tracking for API keys\n- Flexible authentication middleware\n- Swagger documentation\n\n## Setup\n\n### Prerequisites\n- Node.js 18+\n- PostgreSQL database\n\n### Installation\n\n1. Install dependencies:\n```bash\nnpm install\n```\n\n2. Configure environment variables in `.env`:\n```env\nPORT=3000\nDB_HOST=localhost\nDB_PORT=5432\nDB_USERNAME=postgres\nDB_PASSWORD=password\nDB_NAME=auth_api_key_db\nJWT_SECRET=your-secret-key\nJWT_EXPIRES_IN=1h\nJWT_REFRESH_SECRET=your-refresh-secret\nJWT_REFRESH_EXPIRES_IN=7d\n```\n\n3. Create PostgreSQL database:\n```sql\nCREATE DATABASE auth_api_key_db;\n```\n\n4. Start the application:\n```bash\nnpm run start:dev\n```\n\nThe application will run on `http://localhost:3000`\n\n## API Documentation\n\nSwagger documentation is available at: `http://localhost:3000/api/docs`\n\n## Usage Examples\n\n### 1. Register a User\n```bash\ncurl -X POST http://localhost:3000/auth/signup \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"user@example.com\",\n    \"password\": \"Password123!\",\n    \"name\": \"John Doe\"\n  }'\n```\n\nResponse:\n```json\n{\n  \"user\": {\n    \"id\": \"uuid\",\n    \"email\": \"user@example.com\",\n    \"name\": \"John Doe\"\n  },\n  \"accessToken\": \"eyJhbGc...\",\n  \"refreshToken\": \"eyJhbGc...\"\n}\n```\n\n### 2. Login\n```bash\ncurl -X POST http://localhost:3000/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"user@example.com\",\n    \"password\": \"Password123!\"\n  }'\n```\n\n### 3. Create API Key\n```bash\ncurl -X POST http://localhost:3000/keys/create \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\" \\\n  -d '{\n    \"name\": \"My Service API Key\",\n    \"expiresAt\": \"2025-12-31T23:59:59Z\"\n  }'\n```\n\nResponse:\n```json\n{\n  \"id\": \"uuid\",\n  \"key\": \"sk_64characterhexstring...\",\n  \"name\": \"My Service API Key\",\n  \"expiresAt\": \"2025-12-31T23:59:59.000Z\",\n  \"createdAt\": \"2025-01-15T10:30:00.000Z\"\n}\n```\n\n### 4. Access Protected Route with JWT\n```bash\ncurl -X GET http://localhost:3000/protected/user-only \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n### 5. Access Protected Route with API Key\n```bash\ncurl -X GET http://localhost:3000/protected/service-only \\\n  -H \"x-api-key: sk_your_api_key_here\"\n```\n\n### 6. Access Flexible Route (Both JWT and API Key)\n```bash\n# With JWT\ncurl -X GET http://localhost:3000/protected/flexible \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n\n# With API Key\ncurl -X GET http://localhost:3000/protected/flexible \\\n  -H \"x-api-key: sk_your_api_key_here\"\n```\n\n### 7. List API Keys\n```bash\ncurl -X GET http://localhost:3000/keys \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n### 8. Revoke API Key\n```bash\ncurl -X DELETE http://localhost:3000/keys/KEY_ID \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n```\n\n## Architecture\n\n### Database Schema\n\n**Users Table:**\n- id (UUID, Primary Key)\n- email (Unique)\n- password (Hashed)\n- name\n- isActive\n- refreshToken\n- createdAt\n- updatedAt\n\n**API Keys Table:**\n- id (UUID, Primary Key)\n- key (Unique, Format: sk_64chars)\n- name\n- userId (Foreign Key)\n- isActive\n- expiresAt\n- lastUsedAt\n- createdAt\n- updatedAt\n\n### Authentication Flow\n\n**User Authentication (JWT):**\n1. User signs up or logs in\n2. Server generates JWT access token and refresh token\n3. Client stores tokens\n4. Client sends Bearer token in Authorization header\n5. Server validates JWT and grants access\n\n**Service Authentication (API Key):**\n1. User creates API key via authenticated endpoint\n2. Server generates unique API key (sk_prefix + 64 hex chars)\n3. Service stores API key securely\n4. Service sends API key in x-api-key header\n5. Server validates API key and grants access\n\n### Guards\n\n- **JwtAuthGuard**: Validates JWT Bearer tokens (user access)\n- **ApiKeyAuthGuard**: Validates API keys (service access)\n- **FlexibleAuthGuard**: Accepts both JWT and API keys\n\n## Security Features\n\n- Passwords hashed with bcrypt (10 rounds)\n- JWT tokens with expiration\n- API keys with optional expiration\n- API key revocation support\n- Last used tracking for API keys\n- Inactive user/key blocking\n- Secure API key generation (crypto.randomBytes)\n\n## Project Structure\n\n```\nsrc/\n├── auth/\n│   ├── dto/\n│   ├── strategies/\n│   ├── auth.controller.ts\n│   ├── auth.service.ts\n│   └── auth.module.ts\n├── api-keys/\n│   ├── dto/\n│   ├── api-keys.controller.ts\n│   ├── api-keys.service.ts\n│   └── api-keys.module.ts\n├── users/\n│   ├── users.service.ts\n│   └── users.module.ts\n├── common/\n│   ├── guards/\n│   └── decorators/\n├── database/\n│   ├── entities/\n│   └── data-source.ts\n├── app.controller.ts\n├── app.module.ts\n└── main.ts\n```\n\n## Testing\n\nUse the Swagger UI at `http://localhost:3000/api/docs` to test all endpoints interactively.\n\n## Production Considerations\n\n1. Change JWT secrets in production\n2. Set `synchronize: false` in TypeORM config\n3. Use migrations for database schema changes\n4. Implement rate limiting\n5. Add request logging\n6. Use HTTPS\n7. Implement refresh token rotation\n8. Add API key usage analytics\n9. Implement API key rate limits per key\n10. Add webhook support for key events\n\n## License\n\nMIT\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftulbadex%2Fnestjs-auth-api-key-system","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftulbadex%2Fnestjs-auth-api-key-system","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftulbadex%2Fnestjs-auth-api-key-system/lists"}