AIC.Core.Identity.Data.Services 2026.6.18.1

dotnet add package AIC.Core.Identity.Data.Services --version 2026.6.18.1
                    
NuGet\Install-Package AIC.Core.Identity.Data.Services -Version 2026.6.18.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AIC.Core.Identity.Data.Services" Version="2026.6.18.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AIC.Core.Identity.Data.Services" Version="2026.6.18.1" />
                    
Directory.Packages.props
<PackageReference Include="AIC.Core.Identity.Data.Services" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add AIC.Core.Identity.Data.Services --version 2026.6.18.1
                    
#r "nuget: AIC.Core.Identity.Data.Services, 2026.6.18.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package AIC.Core.Identity.Data.Services@2026.6.18.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=AIC.Core.Identity.Data.Services&version=2026.6.18.1
                    
Install as a Cake Addin
#tool nuget:?package=AIC.Core.Identity.Data.Services&version=2026.6.18.1
                    
Install as a Cake Tool

AIC Core Libraries

Transforming Industry Through Technology

AIC — Aerospace, Intelligence & Cyber — provides cutting-edge, mission-ready software components powering secure, data-driven systems for the UK defence and national security sector.


Executive Summary

This repository contains the comprehensive enterprise .NET 10 library ecosystem developed by AIC (Aerospace Intelligence Cyber) for high-assurance environments spanning Defence, Government, and critical national infrastructure.

The solution provides 50+ modular packages implementing:

  • Data persistence abstractions supporting Entity Framework Core, MongoDB, MongoDB Realm, and Azure Cosmos DB
  • Enterprise-grade security & cryptography including post-quantum algorithms, asymmetric/symmetric encryption, and certificate management
  • Identity & access management with multi-tenant support, RBAC, audit logging, and API key/JWT authentication
  • Vector search & embeddings for AI/ML workloads via MongoDB Atlas Vector Search
  • Advanced middleware for rate limiting, geo-IP policies, authentication flows, and quota enforcement
  • Comprehensive caching abstractions supporting in-memory and distributed patterns

All packages follow SOLID principles, enforce deterministic builds, include SourceLink tracing, and are published automatically via Azure DevOps CI/CD pipelines.


Core Architecture

Design Principles

  • Modular & Composable: Each package is independently versioned and can be consumed alone or as part of a larger stack
  • SOLID & DRY: Strict adherence to Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles
  • Async-First: Full async/await support throughout, enabling scalable server applications
  • Generic Abstractions: Heavy use of generic interfaces (e.g., IRepository<TEntity, TId>, IDataService<TModel>) to reduce boilerplate
  • High-Assurance Security: Built for air-gapped and connected environments with cryptographic integrity checks
  • Multi-Tenant Ready: Built-in tenant and organisation scoping, quota enforcement, and organisational audit trails

Dependency Injection Pattern

All packages provide extension methods for seamless DI registration:

services
    .AddIdentityDataServices()
    .AddCachingServices()
    .AddCryptographyServices()
    .AddDataServices();

Packages & Capabilities

1. Data Access Layer

Purpose: Unified abstractions and implementations for persistent storage across multiple database engines.

Core Abstractions
  • AIC.Core.Data
    • IRepository<TEntity, TId> — Generic repository interface supporting create, read, update, delete, and complex queries
    • IEntity, IVectorisedEntity — Base entity contracts with ID and metadata support
    • IHasDisplayName, IHasId — Composable capability interfaces
    • SortDirection enum for query ordering
Multi-Database Support

Entity Framework Core

  • AIC.Core.Data.EntityFramework
    • BaseEntityFrameworkCoreRepository<TEntity, TId> — Full LINQ support with lazy loading, eager loading, and expression trees
    • Supports parameterized queries, complex predicates, and navigation property includes
    • Automatic change tracking and SaveChanges batching

MongoDB

  • AIC.Core.Data.MongoDb

    • BaseMongoDbRepository<TModel> — MongoDB-native repository with BSON serialization
    • Document-oriented queries with flexible schema evolution
    • Index management and aggregation pipeline support
  • AIC.Core.Data.MongoDb.Realm

    • BaseMongoDbRealmRepository<TModel> — MongoDB Realm-specific implementation for offline-first mobile scenarios
    • Sync-enabled data persistence with conflict resolution
    • Local realm management and real-time synchronization

Vector Search & Embeddings

  • AIC.Core.Data.MongoDb + Vector Extensions
    • BaseVectorisedMongoDbRepository<TModel> — Advanced vector search via MongoDB Atlas Vector Search
    • SearchVectorAsync() — Cosine similarity search over embeddings with configurable topK results
    • SearchVectorWithScoreAsync() — Returns both documents and relevance scores
    • SearchOrganisationVectorAsync() — Scoped vector search per organisation (multi-tenant aware)
    • Support for AI/ML embedding fields, semantic search, and RAG (Retrieval-Augmented Generation) workloads

Azure Cosmos DB

  • AIC.Core.Data.CosmosDb
    • BaseCosmosDbRepository<TEntity, TId> — Cosmos DB SDK integration
    • Partition key aware queries for global scale
    • Consistency level configuration and cross-partition query support
Generic Data Services
  • AIC.Core.Data.Services
    • BaseDataService<TModel, TId> — Generic CRUD service wrapping repositories
    • Standardised naming: GetByIdAsync(), GetAllAsync(), CreateAsync(), UpdateAsync(), DeleteByIdAsync()
    • Automatic logging and error handling
    • Supports batch operations and transaction coordination
Expression & Query Utilities
  • AIC.Core.Data.Extensions.Expressions — Expression tree utilities for composable query building
  • AIC.Core.Data.Models.References — Shared model references across solutions

2. Identity & Access Management

Purpose: Enterprise-grade user, organisation, tenant, and permission management with audit trails and multi-factor access control.

Core Models & Contracts
  • AIC.Core.Identity.Models
    • IIdentityService — Primary identity contract (user provisioning, attribute management, lock/unlock operations)
    • IGetUserRequest, IGetUserResponse — Request/response envelopes with organisation scoping
    • API key, JWT, and user attribute models
    • Comprehensive exception hierarchy: QuotaExceededException, ApiKeyInvalidException, RateLimitExceededException, etc.
User & Vault Management
  • AIC.Core.Identity.Data.Services
    • IIdentityService + IdentityService — Full user lifecycle (create, retrieve, update, lock, unlock, provision)
    • IVaultService + VaultService — Secure credential storage, key derivation, and secrets management
    • IUserService + UserService — User-specific operations with organisational scoping
    • IAuditService + AuditService — Comprehensive audit logging for all identity operations
Multi-Tenancy & RBAC
  • AIC.Core.Identity.Data.Services
    • BaseRbacDataService<TModel, TId> — Role-Based Access Control base service with resource-level permissions
    • BaseRbacTenantDataService — Tenant-specific RBAC (all operations scoped to tenant)
    • BaseRbacTenantOrganisationDataService — Organisation-wide RBAC with cross-tenant boundaries
Subscriptions Management
  • AIC.Core.Identity.Subscriptions.Models — Subscription domain models
  • AIC.Core.Identity.Subscriptions.Models.MongoDb — MongoDB-specific subscription persistence
  • AIC.Core.Identity.Subscriptions.Services — Subscription lifecycle and entitlement logic
  • AIC.Core.Identity.Subscriptions.Models.References — Reference data for subscription types
Multi-Tenant Organization Hierarchy
  • AIC.Core.Identity.Tenants.Models — Tenant domain models
  • AIC.Core.Identity.Tenants.Models.MongoDb — MongoDB tenant persistence
  • AIC.Core.Identity.Tenants.Models.References — Reference data and lookup tables
Audit & Compliance
  • AIC.Core.Identity.Data.Services
    • AuditService — Tracks all identity operations with user IDs, timestamps, actions, and results
    • Organisational audit trail segregation
    • Immutable audit log append-only design
Extension Methods
  • AIC.Core.Identity.Extensions — Helper methods for identity operations, token generation, and claim extraction

3. Authentication & Authorization

JWT (JSON Web Tokens)
  • AIC.Core.Identity.Data.Services.Jwt

    • IAccessTokenService + JwtAccessTokenService — Issues short-lived access tokens
    • IRefreshTokenService + JwtRefreshTokenService — Manages token refresh flows
    • IJwtKeyMaterialService + RsaJwtKeyMaterialService — RSA-based key material provisioning
    • ISigningCredentialsProvisionService + RsaSigningCredentialsProvisionService — Signing credential management
  • AIC.Core.Identity.Extensions.Jwt

    • JwtAuthServiceCollectionExtensions — DI registration for JWT authentication
    • JwtAuthenticationServiceCollectionExtensions — Full JWT pipeline configuration
    • Bearer token validation, claim extraction, and policy enforcement
API Key Management
  • JWT access tokens embed ApiKeyMetadata as claims
    • Rate limit quotas per API key (requests per time window)
    • Geo-IP restrictions (CIDR-based IP matching)
    • Signature and expiration validation
    • Extensible metadata for custom policies
Authentication Middleware
  • AIC.Core.Identity.Data.Services.Middleware
    • AuthenticationServiceContextMiddleware — Extracts and validates auth tokens, populates user context
    • TokenValidationErrorMiddleware — Handles JWT validation failures with detailed error responses
    • Claims extraction and principal construction
Authorization & Audit Middleware
  • AuthorizationAuditMiddleware — Logs all authenticated requests with action, resource, outcome, and timing
  • Multi-tenant scoping ensures audit logs are segregated
Geo-IP & Network Policies
  • IpGeoPolicyMiddleware — Validates IP address geolocation against API key restrictions
  • IGeoResolver + DefaultGeoResolver — Geolocation lookup (extensible for custom providers)
  • IIpMatcher + CidrIpMatcher — CIDR block matching for IP validation
Rate Limiting
  • QuotaMiddleware — Enforces per-user and per-API-key rate limits
  • Partitioned rate limiters with configurable windows and permit counts
  • RateLimitExceededException for backpressure signaling
Web API Extensions
  • AIC.Core.Identity.Extensions.WebApi
    • WebApiExtensions — Comprehensive ASP.NET Core integration
    • Problem Details mapping for standardised error responses
    • Rate limiting configuration with API key metadata integration
    • Middleware registration helpers
    • Service discovery and dependency injection orchestration
Controllers
  • AIC.Core.Identity.Data.Controllers.Authentication
    • AuthenticationController — RESTful endpoints for login, token refresh, logout

4. Security & Cryptography

Purpose: Enterprise cryptographic primitives supporting post-quantum algorithms, certificate management, and secure key operations.

Core Abstractions
  • AIC.Core.Security.Cryptography
    • IAsymmetricCryptographyProvider<TAlgorithm> — RSA, ECDSA, post-quantum algorithm abstraction
    • ISymmetricCryptographyProvider<TAlgorithm> — AES and other symmetric cipher abstraction
    • IHashProvider — Cryptographic hash function abstraction (SHA-256, SHA-3, BLAKE2, etc.)
    • ICryptographicAsyncStream — Stream-based encryption/decryption for large payloads
Asymmetric Cryptography

RSA Support

  • AIC.Core.Security.Cryptography.Asymmetric.RSA
    • Full RSA-2048, RSA-3072, RSA-4096 support
    • Signing, verification, encryption, decryption
    • PKCS#1 v1.5 and OAEP padding modes

Post-Quantum Algorithms

  • AIC.Core.Security.Cryptography.Asymmetric.Quantum
  • AIC.Core.Security.Cryptography.Asymmetric.Quantum.BouncyCastle
    • CRYSTALS-Kyber (key encapsulation) — quantum-resistant key exchange
    • CRYSTALS-Dilithium (signatures) — quantum-resistant digital signatures
    • ML-KEM, ML-DSA standards support
    • Hybrid classical+quantum signing for transition strategies

X.509 Certificates

  • AIC.Core.Security.Cryptography.Asymmetric.Certificates

    • Certificate generation, parsing, validation
    • Distinguished name handling, extension management
    • Self-signed and CA-signed certificate chains
  • AIC.Core.Security.Cryptography.Asymmetric.Certificates.Quantum

  • AIC.Core.Security.Cryptography.Asymmetric.Certificates.Quantum.BouncyCastle

    • Post-quantum certificate generation and validation
    • Quantum algorithm OIDs and ASN.1 encoding
    • Future-proof PKI infrastructure support
Symmetric Cryptography

AES Support

  • AIC.Core.Security.Cryptography.Symmetric.AES
    • AES-128, AES-192, AES-256 support
    • CBC, CTR, GCM modes
    • Single-round and double-round (nested) encryption for additional security
    • BouncyCastle implementations as alternative to .NET native
Hashing & Message Digests
  • AIC.Core.Security.Cryptography.Hashing

    • SHA-256, SHA-512 support
    • Extensible for SHA-3, BLAKE2, etc.
  • AIC.Core.Security.Cryptography.Hashing.BouncyCastle

    • BouncyCastle-backed hashing for FIPS compliance or air-gapped environments
    • Deterministic hash output for reproducible builds
Extension Methods & Utilities
  • AIC.Core.Security.Cryptography.Asymmetric.Extensions — Helper methods for key generation, encoding, format conversion
  • AIC.Core.Security.Cryptography.Hashing.Extensions — Hash computation shortcuts and verification helpers

5. Caching

Purpose: Flexible caching abstractions supporting in-memory and distributed cache implementations.

Core Abstractions
  • AIC.Core.Caching
    • ICache — Generic cache interface with Get, Set, Remove, Clear operations
    • ITypedCache<T> — Strongly-typed cache for specific model types
    • TTL (time-to-live) support with automatic expiration
    • Cache statistics and monitoring
Implementations

In-Memory

  • AIC.Core.Caching.InMemory
    • InMemoryCache — .NET MemoryCache wrapper
    • Process-local caching suitable for single-instance deployments
    • Fast, low-latency access with eviction policies

Microsoft Memory Cache Adapter

  • AIC.Core.Caching.MicrosoftMemoryCache
    • Wrapper around Microsoft.Extensions.Caching.Memory.IMemoryCache
    • Integrates with standard .NET Core DI
    • Sliding expiration and absolute expiration support
Cache Extensions & Utilities
  • AIC.Core.Caching Extensions
    • CacheExtensions — Convenience methods for cache-aside pattern, lazy loading, bulk operations
    • Async-friendly cache access patterns
    • Typed cache helpers

6. Logging & Observability

Core Logging
  • AIC.Core.Logging
    • Abstraction over Microsoft.Extensions.Logging
    • Structured logging with context propagation
Serilog Integration
  • AIC.Core.Logging.Serilog
    • SerilogLoggingPolicyMiddleware — Middleware for structured request/response logging
    • Event enrichment with request context, user IDs, tenant IDs
    • Sink configuration for console, file, Azure Monitor, Seq
Extension Methods
  • AIC.Core.Logging.Extensions — Helper methods for common logging patterns

7. Utilities & Extensions

  • AIC.Core.Extensions — General-purpose extension methods for strings, collections, reflection, and domain operations

Advanced Features

Multi-Tenant Architecture

Every data service includes built-in organisational and tenant scoping:

public class TenantDataService : BaseRbacTenantDataService<Model>
{
    public async Task GetAsync(Guid tenantId)
    {
        // Automatically scoped to tenantId; cross-tenant access rejected
        return await GetByIdAsync(modelId);
    }
}

Quota & Rate Limiting

API keys carry quota metadata:

  • Rate limiting: Requests per time window (1-minute, 5-minute windows, custom)
  • Enforcement: Partitioned rate limiters by API key or user
  • Rejection handling: Returns HTTP 429 (Too Many Requests) with retry-after headers
// Automatically enforced by middleware
services.AddRateLimiter(options => { /* configured per API key */ });

Audit Logging

Every identity operation is logged:

  • User performing action
  • Resource affected
  • Action type (create, update, delete, etc.)
  • Timestamp and duration
  • Success/failure status
  • IP address and user agent

Vector Search & AI Integration

MongoDB Atlas vector search enables semantic queries:

var results = await repository.SearchVectorAsync(embeddingVector, topK: 10);
var withScores = await repository.SearchVectorWithScoreAsync(embeddingVector);

Suitable for:

  • Semantic search over document collections
  • Recommendation engines
  • RAG (Retrieval-Augmented Generation) pipelines
  • Anomaly detection

Organisational Catch-All Quotas

TargetType.Any quotas act as wildcards:

// This quota applies to all request types
var catchAllQuota = quotas.Where(q => q.TargetType == TargetType.Any || q.TargetType == targetType);

Enables org-level policies with user-level overrides.


Security Posture

High-Assurance Design

  • Built for air-gapped and connected environments
  • No external dependencies for core cryptography
  • BouncyCastle alternative implementations for FIPS-140 compliance
  • Deterministic, reproducible builds with embedded SourceLink

Cryptographic Agility

  • Support for both classical (RSA, AES, SHA-256) and post-quantum algorithms
  • Hybrid signing strategies for gradual transition
  • Algorithm OID flexibility for future standardization

Secrets Management

  • VaultService for secure credential storage
  • Key derivation with salted hashing
  • Audit-logged credential operations
  • No plaintext secrets in logs

Network & Access Control

  • Geo-IP restriction enforcement via CIDR blocks
  • Rate limiting with per-user/per-key quotas
  • API key metadata tainting (can't be used elsewhere without permission)
  • Organisational boundary enforcement

Getting Started

Installation

Each package is available via NuGet with the AIC.Core.* prefix:

# Identity & Access
dotnet add package AIC.Core.Identity.Data.Services
dotnet add package AIC.Core.Identity.Extensions.Jwt
dotnet add package AIC.Core.Identity.Extensions.WebApi

# Data Persistence
dotnet add package AIC.Core.Data.Services
dotnet add package AIC.Core.Data.MongoDb
dotnet add package AIC.Core.Data.EntityFramework

# Security & Cryptography
dotnet add package AIC.Core.Security.Cryptography.Asymmetric.RSA
dotnet add package AIC.Core.Security.Cryptography.Asymmetric.Quantum.BouncyCastle
dotnet add package AIC.Core.Security.Cryptography.Symmetric.AES

# Caching
dotnet add package AIC.Core.Caching.MicrosoftMemoryCache

# Logging
dotnet add package AIC.Core.Logging.Serilog

Complete Startup Example

using AIC.Core.Identity.Extensions;
using AIC.Core.Identity.Extensions.Jwt;
using AIC.Core.Identity.Extensions.WebApi;
using AIC.Core.Data.Services;
using AIC.Core.Caching;
using Microsoft.Extensions.DependencyInjection;

// Build service collection
var services = new ServiceCollection();

// Register all AIC services
services
    .AddIdentityDataServices()
    .AddIdentityJwtServices(Configuration)
    .RegisterWebApiDependencies(Configuration)
    .AddDataServices()
    .AddCachingServices()
    .AddLoggingServices();

var provider = services.BuildServiceProvider();

// Use services
var identityService = provider.GetRequiredService<IIdentityService>();
var userResponse = await identityService.GetUserAsync(getUserRequest);

var userService = provider.GetRequiredService<IUserService>();
var user = await userService.GetByIdAsync(userId);

var cache = provider.GetRequiredService<ICache>();
await cache.SetAsync("key", "value", TimeSpan.FromMinutes(5));

Building Locally

# Restore dependencies
dotnet restore

# Build the solution
dotnet build -c Release

# Run all tests
dotnet test

# Generate NuGet packages locally
dotnet pack -c Release

Build output:

  • DLL assemblies: bin/Release/net10.0/
  • Symbol packages: artifacts/packages/*.snupkg
  • NuGet packages: artifacts/packages/*.nupkg

Typical Project Structure

MyApplication/
├── MyApplication.Web/              # ASP.NET Core / Blazor app
│   ├── Program.cs                  # DI & middleware registration
│   └── Controllers/                # API controllers
├── MyApplication.Services/         # Business logic layer
│   ├── UserService.cs             # Orchestrates identity operations
│   └── DataService.cs             # Data access wrapper
└── MyApplication.Models/          # Domain models
    ├── User.cs
    └── Tenant.cs

// Program.cs registration
services
    .AddIdentityDataServices()
    .AddIdentityExtensions()
    .AddDataServices()
    .AddCachingServices();

app.UseWebApi();  // Registers middleware pipeline

Architecture Patterns

Repository Pattern

All data access flows through IRepository<TEntity, TId>:

public interface IRepository<TEntity, in TId> where TEntity : class where TId : struct
{
    Task<TEntity> GetModelAsync(TId id);
    Task<IEnumerable<TEntity>> GetModelsAsync();
    Task<TEntity> CreateOrUpdateAsync(TEntity entity);
    Task<bool> DeleteAsync(TId id);
}

Implementations:

  • BaseEntityFrameworkCoreRepository — EF Core with LINQ support
  • BaseMongoDbRepository — MongoDB with document queries
  • BaseCosmosDbRepository — Cosmos DB with partition-aware queries
  • BaseVectorisedMongoDbRepository — Vector search extension

Service Layer

Generic BaseDataService<TModel, TId> wraps repositories:

public class BaseDataService<TModel, TId> where TModel : class where TId : struct
{
    public async ValueTask<TModel> GetByIdAsync(TId id) { /* delegates to repository */ }
    public async ValueTask<IEnumerable<TModel>> GetAllAsync(Expression<Func<TModel, bool>>? predicate = null) { }
    public async ValueTask<TModel> CreateAsync(TModel model) { }
    public async ValueTask<TModel> UpdateAsync(TModel model) { }
    public async ValueTask<bool> DeleteByIdAsync(TId id) { }
}

Provides:

  • Consistent method naming (Get*Async, Create*Async, Delete*Async)
  • Automatic logging and error handling
  • Scoped lifetime for security

RBAC (Role-Based Access Control)

BaseRbacDataService<TModel, TId> enforces permissions:

public class BaseRbacDataService<TModel, TId> : BaseDataService<TModel, TId>
{
    // All operations respect user roles and resource permissions
    public async Task<TModel> GetByIdAsync(TId id) 
    { 
        var model = await base.GetByIdAsync(id);
        // Check user has read permission on model
        await authorizationService.AuthorizeAsync(user, model, "Read");
        return model;
    }
}

Middleware Pipeline

Authentication and authorization are applied via middleware:

→ AuthenticationServiceContextMiddleware       (Extract JWT, populate HttpContext.User)
→ AuthorizationAuditMiddleware                (Log authenticated action)
→ IpGeoPolicyMiddleware                       (Validate geo restrictions)
→ QuotaMiddleware                             (Rate limiting)
→ TokenValidationErrorMiddleware              (Error mapping)
→ Application Logic (Controllers, Services)

Testing

The solution includes comprehensive test suites:

Test Projects:

  • AIC.Core.Data.MongoDb.Tests — Repository and query tests
  • AIC.Core.Data.CosmosDb.Tests — Cosmos DB integration tests
  • AIC.Core.Security.Cryptography.*.Tests — Cryptography algorithm tests
  • AIC.Core.Identity.Data.Services.Middleware.Tests — Middleware pipeline tests
  • AIC.Core.Identity.Data.Services.Jwt.Tests — JWT token tests

Test Framework: xUnit (with Fluent Assertions, Moq, NUnit conventions)

Coverage:

  • Unit tests for cryptographic operations
  • Integration tests for database operations
  • Middleware pipeline tests
  • Rate limiting and quota tests
  • RBAC permission enforcement tests

Build & Packaging

Versioning Strategy

Versions follow CalVer (Calendar Versioning):