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
                    
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="CG.Infrastructure.Identity" Version="3.10.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CG.Infrastructure.Identity" Version="3.10.2" />
                    
Directory.Packages.props
<PackageReference Include="CG.Infrastructure.Identity" />
                    
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 CG.Infrastructure.Identity --version 3.10.2
                    
#r "nuget: CG.Infrastructure.Identity, 3.10.2"
                    
#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 CG.Infrastructure.Identity@3.10.2
                    
#: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=CG.Infrastructure.Identity&version=3.10.2
                    
Install as a Cake Addin
#tool nuget:?package=CG.Infrastructure.Identity&version=3.10.2
                    
Install as a Cake Tool

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

  1. Application Startup โ†’ ServiceCollectionExtensions โ†’ Identity Services Registration
  2. Configuration Binding โ†’ IdentityConfig โ†’ Service Configuration
  3. Database Orchestration โ†’ DatabaseConfigService โ†’ Authentication/Authorization Services
  4. 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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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