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
<PackageReference Include="AIC.Core.Identity.Data.Services" Version="2026.6.18.1" />
<PackageVersion Include="AIC.Core.Identity.Data.Services" Version="2026.6.18.1" />
<PackageReference Include="AIC.Core.Identity.Data.Services" />
paket add AIC.Core.Identity.Data.Services --version 2026.6.18.1
#r "nuget: AIC.Core.Identity.Data.Services, 2026.6.18.1"
#:package AIC.Core.Identity.Data.Services@2026.6.18.1
#addin nuget:?package=AIC.Core.Identity.Data.Services&version=2026.6.18.1
#tool nuget:?package=AIC.Core.Identity.Data.Services&version=2026.6.18.1
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.DataIRepository<TEntity, TId>— Generic repository interface supporting create, read, update, delete, and complex queriesIEntity,IVectorisedEntity— Base entity contracts with ID and metadata supportIHasDisplayName,IHasId— Composable capability interfacesSortDirectionenum for query ordering
Multi-Database Support
Entity Framework Core
AIC.Core.Data.EntityFrameworkBaseEntityFrameworkCoreRepository<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.MongoDbBaseMongoDbRepository<TModel>— MongoDB-native repository with BSON serialization- Document-oriented queries with flexible schema evolution
- Index management and aggregation pipeline support
AIC.Core.Data.MongoDb.RealmBaseMongoDbRealmRepository<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 ExtensionsBaseVectorisedMongoDbRepository<TModel>— Advanced vector search via MongoDB Atlas Vector SearchSearchVectorAsync()— Cosine similarity search over embeddings with configurable topK resultsSearchVectorWithScoreAsync()— Returns both documents and relevance scoresSearchOrganisationVectorAsync()— 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.CosmosDbBaseCosmosDbRepository<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.ServicesBaseDataService<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 buildingAIC.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.ModelsIIdentityService— 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.ServicesIIdentityService+IdentityService— Full user lifecycle (create, retrieve, update, lock, unlock, provision)IVaultService+VaultService— Secure credential storage, key derivation, and secrets managementIUserService+UserService— User-specific operations with organisational scopingIAuditService+AuditService— Comprehensive audit logging for all identity operations
Multi-Tenancy & RBAC
AIC.Core.Identity.Data.ServicesBaseRbacDataService<TModel, TId>— Role-Based Access Control base service with resource-level permissionsBaseRbacTenantDataService— 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 modelsAIC.Core.Identity.Subscriptions.Models.MongoDb— MongoDB-specific subscription persistenceAIC.Core.Identity.Subscriptions.Services— Subscription lifecycle and entitlement logicAIC.Core.Identity.Subscriptions.Models.References— Reference data for subscription types
Multi-Tenant Organization Hierarchy
AIC.Core.Identity.Tenants.Models— Tenant domain modelsAIC.Core.Identity.Tenants.Models.MongoDb— MongoDB tenant persistenceAIC.Core.Identity.Tenants.Models.References— Reference data and lookup tables
Audit & Compliance
AIC.Core.Identity.Data.ServicesAuditService— 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.JwtIAccessTokenService+JwtAccessTokenService— Issues short-lived access tokensIRefreshTokenService+JwtRefreshTokenService— Manages token refresh flowsIJwtKeyMaterialService+RsaJwtKeyMaterialService— RSA-based key material provisioningISigningCredentialsProvisionService+RsaSigningCredentialsProvisionService— Signing credential management
AIC.Core.Identity.Extensions.JwtJwtAuthServiceCollectionExtensions— DI registration for JWT authenticationJwtAuthenticationServiceCollectionExtensions— Full JWT pipeline configuration- Bearer token validation, claim extraction, and policy enforcement
API Key Management
- JWT access tokens embed
ApiKeyMetadataas 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.MiddlewareAuthenticationServiceContextMiddleware— Extracts and validates auth tokens, populates user contextTokenValidationErrorMiddleware— 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 restrictionsIGeoResolver+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
RateLimitExceededExceptionfor backpressure signaling
Web API Extensions
AIC.Core.Identity.Extensions.WebApiWebApiExtensions— 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.AuthenticationAuthenticationController— 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.CryptographyIAsymmetricCryptographyProvider<TAlgorithm>— RSA, ECDSA, post-quantum algorithm abstractionISymmetricCryptographyProvider<TAlgorithm>— AES and other symmetric cipher abstractionIHashProvider— 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.QuantumAIC.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.QuantumAIC.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 conversionAIC.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.CachingICache— Generic cache interface with Get, Set, Remove, Clear operationsITypedCache<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.InMemoryInMemoryCache— .NETMemoryCachewrapper- 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
- Wrapper around
Cache Extensions & Utilities
AIC.Core.CachingExtensionsCacheExtensions— 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
- Abstraction over
Serilog Integration
AIC.Core.Logging.SerilogSerilogLoggingPolicyMiddleware— 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
VaultServicefor 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 supportBaseMongoDbRepository— MongoDB with document queriesBaseCosmosDbRepository— Cosmos DB with partition-aware queriesBaseVectorisedMongoDbRepository— 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 testsAIC.Core.Data.CosmosDb.Tests— Cosmos DB integration testsAIC.Core.Security.Cryptography.*.Tests— Cryptography algorithm testsAIC.Core.Identity.Data.Services.Middleware.Tests— Middleware pipeline testsAIC.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):