Files
pos-system/microservices/docs/vi/architecture/iam-proposal.md
Ho Ngoc Hai 76d75c753b Migrate
2026-05-23 18:37:02 +07:00

17 KiB

Đề 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 Duende IdentityServer
  • ASP.NET Core Identity cho user management
  • Role-Based Access Control (RBAC)
  • JWT Tokens (Access 15min, Refresh 7 days, RS256 signing)
  • 2FA/MFA Support (TOTP với QR Code và Recovery Codes)
  • Email Verification (Xác thực email qua SMTP)
  • Social Login (Google, Facebook OAuth)
  • Distributed Caching (Redis với ICacheService)

Note

IAM Service đã được triển khai với .NET 10, Clean Architecture, Duende IdentityServer 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

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 Email Verification APIs

Method Endpoint Mô tả Auth
POST /api/v1/auth/send-verification-email Gửi email xác thực
POST /api/v1/auth/confirm-email Xác nhận email với token

4.3 Xác Thực Hai Yếu Tố (2FA) APIs

Method Endpoint Mô tả Auth
POST /api/v1/auth/2fa/enable Bật 2FA (lấy QR code + recovery codes)
POST /api/v1/auth/2fa/verify Xác minh mã TOTP & kích hoạt
POST /api/v1/auth/2fa/disable Tắt 2FA

4.4 Social Login APIs

Method Endpoint Mô tả Auth
GET /api/v1/auth/external-login/{provider} Bắt đầu OAuth flow (Google/Facebook)
GET /api/v1/auth/external-callback Xử lý OAuth callback
GET /api/v1/auth/linked-accounts Lấy danh sách providers đã liên kết

4.5 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.6 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.7 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.8 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.9 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.10 Access Requests APIs (New in Phase 3A)

Method Endpoint Mô tả Auth
POST /api/v1/access-requests Tạo yêu cầu truy cập mới
GET /api/v1/access-requests Lấy danh sách requests của user
GET /api/v1/access-requests/{id} Lấy request theo ID
POST /api/v1/access-requests/{id}/submit Submit request để phê duyệt
POST /api/v1/access-requests/{id}/approve Phê duyệt request
POST /api/v1/access-requests/{id}/reject Từ chối request
DELETE /api/v1/access-requests/{id} Hủy request
GET /api/v1/access-requests/pending Lấy requests đang chờ phê duyệt

4.11 Access Reviews APIs (New in Phase 3B)

Method Endpoint Mô tả Auth
POST /api/v1/access-reviews Tạo access review mới
GET /api/v1/access-reviews/{id} Lấy review theo ID
POST /api/v1/access-reviews/{id}/items Thêm item vào review
POST /api/v1/access-reviews/{id}/start Bắt đầu review campaign
POST /api/v1/access-reviews/{id}/items/{itemId}/review Certify/Revoke item
POST /api/v1/access-reviews/{id}/complete Hoàn thành review

4.12 Privileged Access Management (PAM) APIs (New in Phase 3B)

Method Endpoint Mô tả Auth
POST /api/v1/privileged-access/request Yêu cầu JIT elevated access
GET /api/v1/privileged-access/active Lấy grants đang active
POST /api/v1/privileged-access/{id}/revoke Thu hồi privileged access

4.13 Audit Log APIs (New in Phase 4A)

Method Endpoint Mô tả Auth
GET /api/v1/audit/logs Lấy audit logs (filtered, paginated)

4.14 Compliance APIs (New in Phase 4A)

Method Endpoint Mô tả Auth
POST /api/v1/compliance/reports Tạo compliance report mới
GET /api/v1/compliance/reports Lấy danh sách reports
GET /api/v1/compliance/reports/{id} Lấy report chi tiết
POST /api/v1/compliance/reports/{id}/complete Hoàn thành report
GET /api/v1/compliance/violations Lấy violations chưa giải quyết

4.15 Governance APIs (Planned - Phase 4B)

Note

Các APIs dưới đây là tính năng đang được lên kế hoạch cho Phase 4B.

# Policy Governance
GET    /api/v1/policies
POST   /api/v1/policies
GET    /api/v1/policies/:id/versions
POST   /api/v1/policies/:id/activate

# Risk Management
GET    /api/v1/risk/scores/:userId
POST   /api/v1/risk/calculate

# Security Dashboard
GET    /api/v1/dashboard/security

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 (Completed)

  • Access request/approval workflows (Create → Submit → Approve/Reject)
  • Access review & certification system (Certify/Revoke decisions)
  • Privileged Access Management (PAM) với JIT elevated access
  • Entity configurations với EF Core Value Conversion

Phase 4: Governance (In Progress)

Phase 4A: Audit & Compliance (Completed)

  • AuditLog aggregate với 18 event types
  • ComplianceReport aggregate (GDPR, SOC2, ISO27001, HIPAA)
  • Audit log search & filtering
  • Compliance report generation & violations tracking

Phase 4B: Policy & Risk (Planned)

  • 🔄 PolicyTemplate aggregate với versioning
  • 🔄 RiskScore aggregate & calculation
  • 🔄 Security posture dashboard

Phase 5: Advanced Features (Planned)

  • 🔄 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

Kết Luận

Đề xuất này mở rộng 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