# Đề Xuất Kiến Trúc IAM Service Tài liệu này mô tả đề xuất kiến trúc cho IAM Service (Identity and Access Management Service), mở rộng từ auth-service hiện tại. ## Tổng Quan: Auth Service → IAM Service **IAM Service** cung cấp: - **OAuth2/OpenID Connect** với OpenIddict - **ASP.NET Core Identity** cho user management - **Role-Based Access Control (RBAC)** - **JWT Tokens** (Access 15min, Refresh 7 days) - **MFA Support** (TOTP) > [!NOTE] > IAM Service đã được triển khai với .NET 10, Clean Architecture tại `services/iam-service-net/` --- ## 1. Phạm Vi IAM Service ### 1.1 Identity Management (Quản Lý Danh Tính) #### A. User Lifecycle Management - User CRUD operations - User provisioning/deprovisioning workflows - Bulk user operations (import/export) - User deactivation/reactivation với approval workflow - Account merging/deduplication - User archival (soft delete với retention policy) #### B. Profile Management - Extended attributes (custom fields) - Profile picture upload & management - Contact information (phone, address) - Preferences & settings - Profile versioning/audit trail #### C. Identity Verification - Email verification - Phone/SMS verification - Identity document verification (KYC) - Multi-level verification (verified, pending, rejected) #### D. Organizations & Groups - Organization management (multi-tenant) - Group/Team management - Organization hierarchy - Group-based access control - Organization-level policies ### 1.2 Access Management (Quản Lý Truy Cập) #### A. Advanced Access Control - Just-In-Time (JIT) access provisioning - Privileged Access Management (PAM) - Temporary access grants - Access request/approval workflows - Delegation & impersonation (admin view) - Conditional access policies (location, time, device) #### B. Access Reviews & Certifications - Periodic access reviews - Access certification campaigns - Access analytics & reporting - Risk scoring for access decisions - Anomaly detection (unusual access patterns) ### 1.3 Governance & Compliance (Quản Trị & Tuân Thủ) #### A. Audit & Logging - Compliance reporting (GDPR, SOC2, ISO 27001) - Data retention policies - Audit log search & analytics - Export audit logs #### B. Policy Governance - Policy versioning & rollback - Policy templates library - Policy testing & validation - Policy compliance checks #### C. Risk Management - Risk scoring engine - Risk-based authentication - Threat detection - Incident response workflows - Security posture dashboard --- ## 2. Kiến Trúc Module Structure (Thực Tế) ``` services/iam-service-net/ ├── src/ │ ├── IamService.API/ # Presentation Layer │ │ ├── Controllers/ # AuthController, UsersController, RolesController │ │ ├── Application/ # CQRS Commands, Queries, Handlers │ │ │ ├── Commands/ # RegisterUserCommand, ChangePasswordCommand │ │ │ ├── Queries/ # GetUserQuery, GetUsersQuery │ │ │ └── Validators/ # FluentValidation validators │ │ └── Program.cs # App entry point │ ├── IamService.Domain/ # Domain Layer │ │ ├── AggregatesModel/ # ApplicationUser, ApplicationRole │ │ ├── Events/ # UserCreatedEvent, UserDeletedEvent │ │ ├── Exceptions/ # UserNotFoundException, InvalidCredentialsException │ │ └── SeedWork/ # Entity, IAggregateRoot, IRepository │ └── IamService.Infrastructure/ # Infrastructure Layer │ ├── IamServiceContext.cs # DbContext with Identity + OpenIddict │ ├── Repositories/ # UserRepository, RoleRepository │ └── Services/ # EmailService, TokenService ├── tests/ │ ├── IamService.UnitTests/ │ └── IamService.FunctionalTests/ ├── docs/ ├── Dockerfile └── IamService.slnx ``` ### Sơ Đồ Kiến Trúc Clean Architecture ```mermaid graph TD %% Styling Configuration classDef base fill:#202020,stroke:#505050,color:#fff,stroke-width:1px; classDef core fill:#1a237e,stroke:#3949ab,color:#fff,stroke-width:1px; classDef newModule fill:#1b5e20,stroke:#43a047,color:#fff,stroke-width:1px; classDef database fill:#4a148c,stroke:#7b1fa2,color:#fff,stroke-width:1px; %% Main Service Node IAM[IAM Service]:::core %% Identity Management Subgraph subgraph Identity [Identity Management] direction TB User[User Lifecycle]:::newModule Profile[Profile Mgmt]:::newModule Verify[Verification]:::newModule Org[Org & Groups]:::newModule end %% Access Management Subgraph subgraph Access [Access Management] direction TB Req[Access Requests]:::newModule Review[Access Reviews]:::newModule PAM[PAM]:::newModule Analytics[Analytics]:::newModule end %% Governance Subgraph subgraph Governance [Governance & Compliance] direction TB Comp[Compliance]:::newModule Policy[Policy Gov]:::newModule Risk[Risk Mgmt]:::newModule end %% Database DB[(Neon Database)]:::database %% Relationships IAM --> Identity IAM --> Access IAM --> Governance Identity -.-> DB Access -.-> DB Governance -.-> DB %% Internal Dependencies Access --> Identity Governance ---> Access ``` --- ## 3. Database Schema Mở Rộng ### 3.1 Identity Management Models - **Organization**: Quản lý tổ chức với hierarchy - **Group**: Quản lý nhóm trong organization - **GroupMember**: Thành viên của group - **GroupPermission**: Permissions cho group - **UserProfile**: Thông tin profile mở rộng của user - **IdentityVerification**: Xác thực danh tính (email, phone, document) ### 3.2 Access Management Models - **AccessRequest**: Yêu cầu truy cập - **AccessRequestApprover**: Người phê duyệt request - **AccessReview**: Đánh giá truy cập định kỳ - **AccessReviewItem**: Item trong review ### 3.3 Governance Models - **ComplianceReport**: Báo cáo tuân thủ (GDPR, SOC2, ISO27001) - **PolicyTemplate**: Template cho policies - **RiskScore**: Điểm rủi ro của user --- ## 4. API Endpoints (Thực Tế) ### 4.1 Authentication APIs | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `POST` | `/api/v1/auth/register` | Đăng ký user mới | ❌ | | `POST` | `/connect/token` | OAuth2 token endpoint (login, refresh) | ❌ | | `POST` | `/api/v1/auth/change-password` | Đổi mật khẩu | ✅ | | `POST` | `/api/v1/auth/logout` | Đăng xuất (revoke tokens) | ✅ | ### 4.2 User Management APIs | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `GET` | `/api/v1/users` | Danh sách users (paginated) | ✅ | | `GET` | `/api/v1/users/me` | Thông tin user hiện tại | ✅ | | `GET` | `/api/v1/users/{id}` | Lấy user theo ID | ✅ | | `PUT` | `/api/v1/users/{id}` | Cập nhật user | ✅ | | `DELETE` | `/api/v1/users/{id}` | Xóa user (soft delete) | ✅ | ### 4.3 Role Management APIs | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `GET` | `/api/v1/roles` | Danh sách roles | ✅ | | `POST` | `/api/v1/roles` | Tạo role mới | ✅ Admin | | `PUT` | `/api/v1/roles/{id}` | Cập nhật role | ✅ Admin | | `DELETE` | `/api/v1/roles/{id}` | Xóa role | ✅ Admin | ### 4.4 Organization & Group APIs ✅ (New in Phase 2) | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `GET` | `/api/v1/organizations/{id}` | Lấy tổ chức theo ID | ✅ | | `GET` | `/api/v1/organizations/slug/{slug}` | Lấy tổ chức theo slug | ✅ | | `POST` | `/api/v1/organizations` | Tạo tổ chức mới | ✅ | | `PUT` | `/api/v1/organizations/{id}` | Cập nhật tổ chức | ✅ | | `DELETE` | `/api/v1/organizations/{id}` | Lưu trữ (archive) tổ chức | ✅ | | `GET` | `/api/v1/organizations/{id}/hierarchy` | Lấy phân cấp tổ chức | ✅ | | `GET` | `/api/v1/organizations/{id}/children` | Lấy tổ chức con | ✅ | | `GET` | `/api/v1/groups` | Danh sách groups theo organizationId | ✅ | | `GET` | `/api/v1/groups/{id}` | Lấy group theo ID | ✅ | | `POST` | `/api/v1/groups` | Tạo group mới | ✅ | | `DELETE` | `/api/v1/groups/{id}` | Xóa group (soft delete) | ✅ | | `POST` | `/api/v1/groups/{id}/members` | Thêm thành viên vào group | ✅ | | `DELETE` | `/api/v1/groups/{id}/members/{userId}` | Xóa thành viên khỏi group | ✅ | ### 4.5 User Profile APIs ✅ (New in Phase 2) | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `GET` | `/api/v1/users/{id}/profile` | Lấy profile user | ✅ | | `PUT` | `/api/v1/users/{id}/profile` | Cập nhật profile user | ✅ | | `PUT` | `/api/v1/users/{id}/profile/attributes/{key}` | Đặt profile attribute | ✅ | ### 4.6 Identity Verification APIs ✅ (New in Phase 2) | Method | Endpoint | Mô tả | Auth | |--------|----------|-------|------| | `POST` | `/api/v1/verifications/phone` | Yêu cầu xác thực số điện thoại | ✅ | | `POST` | `/api/v1/verifications/email` | Yêu cầu xác thực email | ✅ | | `POST` | `/api/v1/verifications/{id}/confirm` | Xác nhận với OTP code | ✅ | ### 4.7 Access Management APIs (Planned) ``` # Access Requests GET /api/v1/access/requests POST /api/v1/access/requests PUT /api/v1/access/requests/:id/approve PUT /api/v1/access/requests/:id/reject # Access Reviews GET /api/v1/access/reviews POST /api/v1/access/reviews POST /api/v1/access/reviews/:id/start POST /api/v1/access/reviews/:id/complete GET /api/v1/access/reviews/:id/items # Access Analytics GET /api/v1/access/analytics/usage GET /api/v1/access/analytics/permissions GET /api/v1/access/analytics/risks ``` ### 4.3 Governance APIs ``` # Compliance Reports GET /api/v1/governance/compliance/reports POST /api/v1/governance/compliance/reports/generate GET /api/v1/governance/compliance/reports/:id/export # Policy Governance GET /api/v1/governance/policies/templates POST /api/v1/governance/policies/templates GET /api/v1/governance/policies/:id/versions POST /api/v1/governance/policies/:id/test # Risk Management GET /api/v1/governance/risk/scores GET /api/v1/governance/risk/scores/:userId POST /api/v1/governance/risk/calculate # Reporting GET /api/v1/governance/reports/access-summary GET /api/v1/governance/reports/user-activity GET /api/v1/governance/reports/security-events ``` --- ## 5. Implementation Roadmap ### Phase 1: Foundation ✅ (Completed) - ✅ Migrate từ auth-service sang iam-service (.NET 10 + Duende IdentityServer) - ✅ CQRS với MediatR Pattern - ✅ User Registration, Login, Logout - ✅ Password Management (change-password) - ✅ User Management APIs (CRUD) - ✅ Role Management APIs ### Phase 1.5: Enhanced Security ✅ (Completed) - ✅ Email Verification (send + confirm) - ✅ 2FA/MFA với TOTP (QR Code, Recovery Codes) - ✅ Social Login (Google, Facebook OAuth) - ✅ Distributed Caching với Redis (ICacheService) - ✅ Token Blacklisting cho logout ### Phase 2: Identity Management ✅ (Completed) - ✅ User lifecycle management - ✅ Identity verification (phone, email) - ✅ Organization & Group management - ✅ Profile management with extended attributes (ProfileAttribute entity) ### Phase 3: Access Management (Weeks 9-12) - 🔄 Access request/approval workflows - 🔄 Access review & certification system - 🔄 Access analytics - 🔄 Privileged Access Management (PAM) ### Phase 4: Governance (Weeks 13-16) - 🔄 Compliance reporting engine - 🔄 Policy governance & versioning - 🔄 Risk scoring & management - 🔄 Reporting dashboards ### Phase 5: Advanced Features (Weeks 17-20) - 🔄 Workflow engine - 🔄 Advanced analytics & ML-based insights - 🔄 Integration APIs (SCIM, LDAP sync) - 🔄 Performance optimization & scaling --- ## 6. Lợi Ích Của IAM Service ### 6.1 Cho Doanh Nghiệp - ✅ Tuân thủ (GDPR, SOC2, ISO 27001) - ✅ Quản lý rủi ro bảo mật tốt hơn - ✅ Tự động hóa quy trình quản lý truy cập - ✅ Báo cáo và audit trail đầy đủ - ✅ Hỗ trợ multi-tenant/organization ### 6.2 Cho Developers - ✅ API thống nhất cho identity & access - ✅ Workflow engine linh hoạt - ✅ Extensible architecture - ✅ Comprehensive documentation - ✅ SDK support ### 6.3 Cho End Users - ✅ Self-service profile management - ✅ Transparent access requests - ✅ Better user experience - ✅ Enhanced security với MFA & verification --- ## 7. Migration Strategy ### Từ Auth Service → IAM Service 1. **Rename Service**: `services/auth-service` → `services/iam-service` 2. **Update Package Name**: `@goodgo/auth-service` → `@goodgo/iam-service` 3. **Update Routes**: - Giữ backward compatibility với `/api/v1/auth/*` - Thêm routes mới cho `/api/v1/identity/*`, `/api/v1/access/*`, `/api/v1/governance/*` 4. **Database Migration**: - Thêm schema mới cho identity, access, governance - Giữ nguyên các tables hiện có (backward compatible) 5. **Gradual Rollout**: - Phase 1: Deploy cùng auth-service (dual deployment) - Phase 2: Migrate clients dần dần - Phase 3: Deprecate auth-service khi migration hoàn tất --- ## Kết Luận Đề xuất này mở rộng `auth-service` thành `IAM Service` với đầy đủ các tính năng: - **Identity Management** đầy đủ - **Access Management** nâng cao - **Governance & Compliance** toàn diện - **Workflow automation** linh hoạt Điều này biến service từ authentication/authorization cơ bản thành một IAM platform toàn diện, phù hợp cho enterprise. --- ## Quick Tips ### Mermaid Common Issues - **Syntax Error**: Kiểm tra kỹ các dấu ngoặc `[]`, `{}`, `()` trong node label. - **Connection**: Đảm bảo các mũi tên `-->`, `-.->` đúng cú pháp. - **Indentation**: Subgraph cần thụt đầu dòng đúng cách. ### Color Pattern Reference | Element | Fill Color | Stroke | Text | Usage | |---------|------------|--------|------|-------| | **Base** | `#202020` | `#505050` | `#fff` | Node thông thường | | **Core** | `#1a237e` | `#3949ab` | `#fff` | Node trung tâm, quan trọng | | **Module**| `#1b5e20` | `#43a047` | `#fff` | Module, service con | | **DB** | `#4a148c` | `#7b1fa2` | `#fff` | Database, storage | | **Warn** | `#b71c1c` | `#f44336` | `#fff` | Cảnh báo, lỗi | ### Visual Indicators | Icon | Meaning | |------|---------| | ✅ | Đã hoàn thành / Tốt | | 🔄 | Đang xử lý / Thay đổi | | ⚠️ | Cảnh báo / Lưu ý | | ❌ | Lỗi / Không khuyến khích |