CG.Infrastructure.Identity
3.10.2
dotnet add package CG.Infrastructure.Identity --version 3.10.2
NuGet\Install-Package CG.Infrastructure.Identity -Version 3.10.2
<PackageReference Include="CG.Infrastructure.Identity" Version="3.10.2" />
<PackageVersion Include="CG.Infrastructure.Identity" Version="3.10.2" />
<PackageReference Include="CG.Infrastructure.Identity" />
paket add CG.Infrastructure.Identity --version 3.10.2
#r "nuget: CG.Infrastructure.Identity, 3.10.2"
#:package CG.Infrastructure.Identity@3.10.2
#addin nuget:?package=CG.Infrastructure.Identity&version=3.10.2
#tool nuget:?package=CG.Infrastructure.Identity&version=3.10.2
Infrastructure.Identity
A .NET 9.0 library that provides comprehensive ASP.NET Core Identity infrastructure with Duende IdentityServer integration, designed for enterprise applications requiring unified authentication, authorization, and identity management systems.
๐ Overview
Infrastructure.Identity is a modern, flexible identity library that orchestrates ASP.NET Core Identity, Duende IdentityServer, and custom authentication/authorization services. It provides a clean, unified interface for configuring identity services with support for both in-memory and database-backed configurations, making it ideal for development, testing, and production environments.
๐ Current Status
โ
Production Ready: Comprehensive identity service orchestration
โ
Code Quality: Clean architecture with dependency injection
โ
Modern Patterns: Latest .NET 9.0 features with best practices
โ
Enterprise Grade: Robust error handling and configuration management
โ
Flexible Configuration: Support for multiple deployment scenarios
โ
Database Schema Alignment: Fixed schema mismatches and migrated from stored procedures to SQL queries
โ
Test Configuration: Integrated test configuration directly into project files
โจ Features
- Unified Identity Configuration: Single point of configuration for all identity services
- Duende IdentityServer Integration: Full support for OpenID Connect and OAuth 2.0
- Flexible Deployment Modes: Support for in-memory, database, and hybrid configurations
- ASP.NET Core Identity: Complete user and role management integration
- Test User Support: Built-in test user configuration for development and testing
- Database Orchestration: Automatic coordination of authentication and authorization data
- CORS Configuration: Configurable CORS policies for cross-origin requests
- Cookie Management: Configurable authentication cookie settings
- Event Logging: Comprehensive event logging for debugging and monitoring
๐๏ธ Architecture
Core Components
Infrastructure.Identity/
โโโ Configuration/
โ โโโ IdentityConfig.cs # Identity configuration model
โโโ Data/
โ โโโ DatabaseConfigService.cs # Database configuration orchestration
โโโ Extensions/
โ โโโ ServiceCollectionExtensions.cs # Service registration and configuration
โโโ Interfaces/
โ โโโ IDatabaseConfigService.cs # Database configuration service contract
โโโ Options/
โโโ ConfigOptions.cs # Configuration options and settings
Project Structure
Infrastructure/v3/
โโโ infrastructure_library_identity/ # Main identity library
โ โโโ src/
โ โ โโโ Infrastructure.Identity/ # Source code
โ โโโ tests/
โ โโโ Infrastructure.Identity.Tests/ # Test project
โโโ infrastructure_library_authorization/ # Authorization library
โ โโโ src/
โ โ โโโ Infrastructure.Authorization/ # Source code
โ โโโ tests/
โ โโโ Infrastructure.Authorization.Tests/ # Test project
โโโ infrastructure_library_authentication/ # Authentication library
โโโ src/
โ โโโ Infrastructure.Authentication/ # Source code
โโโ tests/
โโโ Infrastructure.Authentication.Tests/ # Test project
Service Flow
- Application Startup โ ServiceCollectionExtensions โ Identity Services Registration
- Configuration Binding โ IdentityConfig โ Service Configuration
- Database Orchestration โ DatabaseConfigService โ Authentication/Authorization Services
- Identity Server Setup โ Duende IdentityServer โ OpenID Connect/OAuth 2.0
Configuration Modes
The library supports four distinct configuration modes:
- Database Users: Full database-backed identity with persistent storage
- Memory Users: In-memory identity with database configuration store
- Database Test: Database identity with test users for development
- Memory Test: In-memory identity with test users for testing
๐ฏ Key Benefits
1. Unified Configuration
Single method call to configure all identity services:
services.RegisterInfraIdentityServices(configuration, identityConfig, inMemory: false, testUsers: false);
2. Flexible Deployment Scenarios
Support for different deployment configurations:
// Production: Database-backed with real users
services.RegisterInfraIdentityServices(configuration, identityConfig, false, false);
// Development: In-memory with test users
services.RegisterInfraIdentityServices(configuration, identityConfig, true, true);
// Staging: Database-backed with test users
services.RegisterInfraIdentityServices(configuration, identityConfig, false, true);
3. Automatic Service Orchestration
Seamless integration of authentication and authorization services:
public static IServiceCollection RegisterInfraIdentityServices(
this IServiceCollection services,
IConfiguration configuration,
IdentityConfig identityConfig,
bool inMemory,
bool testUsers)
{
// Automatically registers all required services
services.RegisterConfigOptions(configuration);
services.RegisterAuthorizationConfig(configuration, identityConfig);
services.RegisterAuthenticationConfig(configuration);
// Configures ASP.NET Core Identity
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddApplicationUserStores()
.AddDefaultTokenProviders();
// Configures Duende IdentityServer based on mode
services.ConfigureIdentity(inMemory, testUsers, identityConfig);
return services;
}
4. Database Configuration Orchestration
Centralized database setup and data seeding:
public class DatabaseConfigService : IDatabaseConfigService
{
public async Task EnsureConfigData()
{
// Ensures authorization data is properly configured
await authorizationService.EnsureAuthorizationData();
}
public async Task EnsureUserData(string? users)
{
// Ensures authentication data is properly configured
await authenticationService.EnsureAuthenticationData(users);
}
}
5. Configurable Identity Options
Flexible ASP.NET Core Identity configuration:
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 1;
options.User.RequireUniqueEmail = true;
});
๐ง Installation & Setup
Package Reference
<PackageReference Include="Infrastructure.Identity" Version="3.0.0" />
Service Registration
// Program.cs or Startup.cs
using Infrastructure.Identity.Extensions;
using Infrastructure.Identity.Configuration;
// Create identity configuration
var identityConfig = new IdentityConfig
{
Clients = GetClients(),
ApiResources = GetApiResources(),
ApiScopes = GetApiScopes(),
IdentityResources = GetIdentityResources(),
IssuerUri = "https://your-identity-server.com"
};
// Register all identity services
services.RegisterInfraIdentityServices(configuration, identityConfig, inMemory: false, testUsers: false);
Configuration Options
// appsettings.json
{
"ConfigOptions": {
"DbSchema": "dbo",
"SeedDb": true,
"MigrateDb": true,
"AllowedCors": ["https://your-app.com"],
"UsersFile": "users.json",
"ShowAllResources": false
}
}
๐ Usage Examples
Basic Identity Setup
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Configure identity services
var identityConfig = new IdentityConfig
{
Clients = GetClients(),
ApiResources = GetApiResources(),
ApiScopes = GetApiScopes(),
IdentityResources = GetIdentityResources()
};
builder.Services.RegisterInfraIdentityServices(
builder.Configuration,
identityConfig,
inMemory: false,
testUsers: false);
var app = builder.Build();
app.Run();
}
private static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "client",
ClientName = "Client Application",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedScopes = { "api1" }
}
};
}
}
Development Configuration
// Development environment with test users
if (builder.Environment.IsDevelopment())
{
var identityConfig = new IdentityConfig
{
Clients = GetDevelopmentClients(),
ApiResources = GetDevelopmentApiResources(),
ApiScopes = GetDevelopmentApiScopes(),
IdentityResources = GetDevelopmentIdentityResources()
};
builder.Services.RegisterInfraIdentityServices(
builder.Configuration,
identityConfig,
inMemory: true,
testUsers: true);
}
Production Configuration
// Production environment with database persistence
if (builder.Environment.IsProduction())
{
var identityConfig = new IdentityConfig
{
Clients = GetProductionClients(),
ApiResources = GetProductionApiResources(),
ApiScopes = GetProductionApiScopes(),
IdentityResources = GetProductionIdentityResources()
};
builder.Services.RegisterInfraIdentityServices(
builder.Configuration,
identityConfig,
inMemory: false,
testUsers: false);
}
Custom Identity Options
// Customize identity options
services.Configure<IdentityOptions>(options =>
{
// Password requirements
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
// User requirements
options.User.RequireUniqueEmail = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
});
Database Configuration Service Usage
public class StartupService
{
private readonly IDatabaseConfigService _databaseConfigService;
public StartupService(IDatabaseConfigService databaseConfigService)
{
_databaseConfigService = databaseConfigService;
}
public async Task InitializeDatabaseAsync()
{
// Ensure authorization data is configured
await _databaseConfigService.EnsureConfigData();
// Ensure authentication data is configured
await _databaseConfigService.EnsureUserData("users.json");
}
}
๐๏ธ Database Integration
Supported Database Providers
- SQL Server: Primary database provider with full support
- PostgreSQL: Compatible with Entity Framework Core
- SQLite: Lightweight option for development and testing
Current Implementation Status
- โ Entity Models: All entity models properly aligned with database schema
- โ
SQL Queries: Centralized query system in
AuthorizationQueries.cs
- โ Repository Pattern: Clean repository implementations using SQL queries
- โ Transaction Support: Full transaction support for data operations
- โ Schema Validation: Entity models match actual database tables
Database Schema Requirements
The library requires the following database schemas to be available:
- Authentication Schema: ASP.NET Core Identity tables
- Authorization Schema: Duende IdentityServer tables (Clients, ApiResources, ApiScopes, etc.)
- User Management: Custom user and role tables
Migration Support
- Entity Framework Core: Automatic migrations
- DbUp: Manual script-based migrations
- Custom Migrations: Support for custom migration strategies
๐ Security Features
Identity Server Security
- OpenID Connect: Industry-standard authentication protocol
- OAuth 2.0: Authorization framework support
- JWT Tokens: Secure token-based authentication
- Refresh Tokens: Long-lived session management
- PKCE Support: Enhanced security for public clients
Authentication Security
- Password Policies: Configurable password requirements
- Account Lockout: Brute force protection
- Multi-Factor Authentication: Support for 2FA
- Session Management: Configurable session lifetimes
- Cookie Security: Secure authentication cookies
Authorization Security
- Role-Based Access Control: User role management
- Claim-Based Authorization: Flexible permission system
- Resource-Based Security: API resource protection
- Scope-Based Access: Granular permission control
๐ Configuration Modes
Mode 1: Database Users (Production)
services.ConfigureIdentityDatabaseUsers(identityConfig);
- Features: Full database persistence, real users, production-ready
- Use Case: Production applications with user management
- Storage: Database-backed configuration and operational stores
Mode 2: Memory Users (Development)
services.ConfigureIdentityMemoryUsers(identityConfig);
- Features: In-memory configuration, real users, fast startup
- Use Case: Development environments with real user testing
- Storage: In-memory configuration, database operational store
Mode 3: Database Test (Staging)
services.ConfigureIdentityDatabaseTest(identityConfig);
- Features: Database persistence, test users, staging environment
- Use Case: Staging and testing environments
- Storage: Database-backed configuration, test user store
Mode 4: Memory Test (Testing)
services.ConfigureIdentityMemoryTest(identityConfig);
- Features: In-memory configuration, test users, fast testing
- Use Case: Unit testing and integration testing
- Storage: In-memory configuration and test user store
๐งช Testing
Test Configuration
The test project is configured directly in the .csproj
file for better maintainability:
<PropertyGroup>
<MaxCpuCount>1</MaxCpuCount>
<BatchSize>1</BatchSize>
<TestSessionTimeout>30000</TestSessionTimeout>
<TestCaseFilter>TestCategory!=Integration</TestCaseFilter>
</PropertyGroup>
<PropertyGroup>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>cobertura</CoverletOutputFormat>
<CoverletOutput>$(MSBuildThisFileDirectory)TestResults\</CoverletOutput>
<ExcludeByAttribute>Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute</ExcludeByAttribute>
</PropertyGroup>
Test Project Structure
Infrastructure.Identity.Tests/
โโโ Configuration/ # Configuration tests
โโโ Data/ # Database service tests
โโโ Extensions/ # Service extension tests
โโโ Interfaces/ # Interface implementation tests
โโโ Options/ # Configuration options tests
Example Test
[Fact]
public async Task RegisterInfraIdentityServices_WithValidConfig_RegistersAllServices()
{
// Arrange
var services = new ServiceCollection();
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{"ConfigOptions:DbSchema", "dbo"},
{"ConfigOptions:SeedDb", "true"}
})
.Build();
var identityConfig = new IdentityConfig
{
Clients = new List<Client>(),
ApiResources = new List<ApiResource>(),
ApiScopes = new List<ApiScope>(),
IdentityResources = new List<IdentityResource>()
};
// Act
services.RegisterInfraIdentityServices(configuration, identityConfig, true, true);
// Assert
var serviceProvider = services.BuildServiceProvider();
var identityOptions = serviceProvider.GetService<IOptions<IdentityOptions>>();
Assert.NotNull(identityOptions);
}
Integration Testing
[Fact]
public async Task DatabaseConfigService_EnsureConfigData_CallsAuthorizationService()
{
// Arrange
var mockLogger = new Mock<ILogger<DatabaseConfigService>>();
var mockAuthorizationService = new Mock<IAuthorizationDatabaseService>();
var mockAuthenticationService = new Mock<IAuthenticationDatabaseService>();
var service = new DatabaseConfigService(
mockLogger.Object,
mockAuthorizationService.Object,
mockAuthenticationService.Object);
// Act
await service.EnsureConfigData();
// Assert
mockAuthorizationService.Verify(
x => x.EnsureAuthorizationData(),
Times.Once);
}
๐ Dependencies
Core Framework
- .NET 9.0: Target framework
Infrastructure Libraries
- Infrastructure.Authentication (3.0.0): Authentication services and stores
- Infrastructure.Authorization (3.0.0): Authorization services and configuration
- Infrastructure.Configuration (3.0.0): Configuration management and options
- Infrastructure.Core (3.0.0): Core infrastructure components
Identity & Authentication
- Microsoft.AspNetCore.Identity (9.0.2): ASP.NET Core Identity framework
- Duende.IdentityServer (7.1.0): OpenID Connect and OAuth 2.0 server
- Duende.IdentityServer.AspNetIdentity (7.1.0): IdentityServer integration
Configuration & Logging
- Microsoft.Extensions.Configuration (9.0.2): Configuration management
- Microsoft.Extensions.DependencyInjection (9.0.2): Dependency injection
- Microsoft.Extensions.Logging (9.0.2): Logging infrastructure
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Development Guidelines
- Follow C# coding conventions
- Add unit tests for new functionality
- Update documentation for API changes
- Ensure proper dependency injection patterns
- Maintain backward compatibility
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- Documentation: This README and inline code comments
- Issues: Create an issue in the project repository
- Discussions: Use GitHub Discussions for questions and ideas
- Email: Contact the development team directly
๐ฎ Roadmap
- Core Identity Services: ASP.NET Core Identity integration
- Duende IdentityServer: OpenID Connect and OAuth 2.0 support
- Flexible Configuration: Multiple deployment modes
- Database Orchestration: Unified database configuration
- Database Schema Alignment: Fixed schema mismatches and migrated to SQL queries
- Test Configuration: Integrated test configuration and code coverage
- Multi-Tenancy: Support for multi-tenant applications
- Advanced Security: Enhanced security features and policies
- Performance Optimization: Caching and performance improvements
- Monitoring & Metrics: Comprehensive monitoring and telemetry
- Container Support: Docker and container orchestration support
๐ Recent Improvements
Database Schema Alignment (Latest)
- Fixed Schema Mismatches: Resolved
LastAccessed
column issues in entity models - Migrated from Stored Procedures: Replaced all stored procedure calls with SQL queries from
AuthorizationQueries.cs
- Improved Data Consistency: Entity models now properly align with database schema
- Enhanced Error Handling: Better error messages for database-related issues
Test Configuration Integration
- Unified Configuration: Moved test configuration from
runsettings
files to.csproj
files - Code Coverage: Integrated Coverlet code coverage with Cobertura output format
- Test Execution Control: Configurable test execution parameters (MaxCpuCount, BatchSize, etc.)
- Simplified Maintenance: Single source of truth for test configuration
Query System Modernization
- SQL Query Centralization: All database queries now centralized in
AuthorizationQueries.cs
- Consistent Command Types: Standardized on
CommandType.Text
for all database operations - Improved Maintainability: Easier to update and maintain database queries
- Better Performance: Direct SQL execution without stored procedure overhead
Built with โค๏ธ by the Infrastructure Team
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- CG.Infrastructure.Authentication (>= 3.10.2)
- CG.Infrastructure.Authorization (>= 3.10.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
3.10.2 | 144 | 9/1/2025 |
3.10.1 | 141 | 8/21/2025 |
3.10.0 | 134 | 8/21/2025 |
3.9.3 | 151 | 2/26/2025 |
3.9.2 | 146 | 2/25/2025 |
3.9.1 | 158 | 2/20/2025 |
3.9.0 | 154 | 12/10/2024 |
3.0.1 | 176 | 8/13/2024 |
3.0.0 | 189 | 8/12/2024 |
2.0.1 | 264 | 5/16/2023 |
2.0.0 | 236 | 5/15/2023 |
1.0.17 | 543 | 7/13/2022 |
1.0.16 | 516 | 6/21/2022 |
1.0.15 | 497 | 6/21/2022 |
1.0.14 | 515 | 6/21/2022 |
1.0.13 | 524 | 6/21/2022 |
1.0.12 | 514 | 6/21/2022 |
1.0.11 | 513 | 6/21/2022 |
1.0.10 | 516 | 6/21/2022 |
1.0.9 | 529 | 6/21/2022 |
1.0.8 | 495 | 6/21/2022 |
1.0.7 | 489 | 6/21/2022 |
1.0.6 | 503 | 6/21/2022 |
1.0.5 | 517 | 5/30/2022 |
1.0.4 | 486 | 5/30/2022 |
1.0.3 | 505 | 5/30/2022 |
1.0.2 | 493 | 5/30/2022 |
1.0.1 | 489 | 5/26/2022 |
1.0.0 | 490 | 5/26/2022 |