Skip to content

A set of libraries to easily integrate and extend authentication in ASP.NET Core projects, using ASP.NET Core Identity.

License

Notifications You must be signed in to change notification settings

AngeloDotNet/MinimalApi.Identity

Repository files navigation

.NET Modular Dynamic Identity Manager

Visitors

A set of libraries to easily integrate and extend authentication in ASP.NET Core projects, using ASP.NET Core Identity.

🏷️ Introduction

MinimalApi.Identity is a dynamic and modular identity manager for managing users, roles, claims and more for access control in Asp.Net Mvc Core and Web API, using .NET 8 Minimal API, Entity Framework Core and relational database (of your choice).

Important

This library is still under development of new implementations and in the process of creating the related documentation.

🧩 Features

  • Minimal API: Built using .NET 8 Minimal API for a lightweight and efficient implementation.
  • Entity Framework Core: Uses EF Core for data access, making it easy to integrate with your existing database.
  • Modular: The library is designed to be modular, allowing you to add or remove features as needed.
  • Dynamic: Supports dynamic management of users, roles, claims, forms, licensing and policies.
  • Flexible Configuration: Easily configurable via appsettings.json to suit your application's needs.
  • Outbox Pattern: Implement the transactional outbox pattern for reliable email sending.

πŸ› οΈ Installation

Prerequisites

Setup

The library is available on NuGet, just search for Identity.Module.API in the Package Manager GUI or run the following command in the .NET CLI:

dotnet add package Identity.Module.API

βš™οΈ Configuration

The configuration can be completely managed by adding this section to the appsettings.json file:

Warning

The library is still under development, so the configuration may change in future updates.

"Kestrel": {
    "Limits": {
        "MaxRequestBodySize": 5242880
    }
},
"ConnectionStrings": {
    "DatabaseType": "sqlserver",
    "SQLServer": "Data Source=[HOSTNAME];Initial Catalog=IdentityManager;User ID=[USERNAME];Password=[PASSWORD];Encrypt=False",
    "MigrationsAssembly": "MinimalApi.Identity.Migrations.SQLServer"
},
"JwtOptions": {
    "Issuer": "[ISSUER]",
    "Audience": "[AUDIENCE]",
    "SecurityKey": "[SECURITY-KEY]", // Must be 512 characters long
    "ClockSkew": "00:05:00", 
    "AccessTokenExpirationMinutes": 60, 
    "RefreshTokenExpirationMinutes": 60, 
    "RequireUniqueEmail": true,
    "RequireDigit": true,
    "RequiredLength": 8,
    "RequireUppercase": true,
    "RequireLowercase": true,
    "RequireNonAlphanumeric": true,
    "RequiredUniqueChars": 4,
    "RequireConfirmedEmail": true,
    "MaxFailedAccessAttempts": 3,
    "AllowedForNewUsers": true,
    "DefaultLockoutTimeSpan": "00:05:00" 
},
"SmtpOptions": {
    "Host": "smtp.example.org",
    "Port": 25,
    "Security": "StartTls",
    "Username": "Username del server SMTP",
    "Password": "Password del server SMTP",
    "Sender": "MyApplication <[email protected]>",
    "MaxRetryAttempts": 10
},
"ApplicationOptions": {
    
    "ErrorResponseFormat": "List"
},
"FeatureFlagsOptions": {
    "EnabledFeatureLicense": true,
    "EnabledFeatureModule": true
},
"HostedServiceOptions": {
    "IntervalEmailSenderMinutes": 5
},
"UsersOptions": {
    "AssignAdminUsername": "admin",
    "AssignAdminEmail": "[email protected]",
    "AssignAdminPassword": "StrongPassword",
    "PasswordExpirationDays": 90
},
"ValidationOptions": {
    "MinLength": 3,
    "MaxLength": 50,
    "MinLengthDescription": 5,
    "MaxLengthDescription": 100
}

Note

For migrations you can use a specific project to add to your solution, then configuring the assembly in ConnectionStrings:MigrationsAssembly, otherwise leave it blank and the assembly containing the Program.cs class will be used.

πŸ—ƒοΈ Database

Configuration

The library uses Entity Framework Core to manage the database.

The connection string is configured in the ConnectionStrings section of the appsettings.json file.

  • Database Type: Set via ConnectionStrings:DatabaseType (supported values: sqlserver)

After setting the type of database you want to use, modify the corresponding connection string.

Migrations

Tip

To update the database schema you need to create migrations, they will be applied automatically at the next application startup.

To create database migrations select MinimalApi.Identity.Core as the default project from the drop-down menu in the Package Manager Console and run the command: Add-Migration MIGRATION-NAME

Example: Add-Migration InitialMigration -Project MinimalApi.Identity.Migrations.SQLServer

Note

if you use a separate project for migrations (It is recommended to add a reference in the project name to the database used, in this case it is SQL Server), make sure to set the -Project parameter to the name of that project.

πŸ”° Feature Flags

🚧 coming soon

πŸ’‘ Usage Examples

Warning

The library is still under development, so the Program.cs configuration may change in future updates.

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var programOptions = RegisterServicesExtensions.AddPublicOptions<Program>(new ProgramOptions(), builder.Configuration);

        builder.Services.AddRegisterDefaultServices<MinimalApiAuthDbContext>(builder.Configuration, options =>
        {
            options.DatabaseType = programOptions.DatabaseType;
            options.MigrationsAssembly = programOptions.MigrationsAssembly;
            options.JwtOptions = programOptions.JwtOptions;
            options.FeatureFlags = programOptions.FeatureFlagsOptions;
            options.FormatErrorResponse = programOptions.FormatErrors;
        });

        //If you need to register services with a lifecycle other than Transient, do not modify this configuration,
        //but create one (or more) duplicates of this configuration, modifying it as needed.
        builder.Services.AddRegisterServices(options =>
        {
            options.Interfaces = [typeof(IAuthService)]; // Register your interfaces here, but do not remove the IAuthService service.
            options.StringEndsWith = "Service"; // This will register all services that end with "Service" in the assembly.
            options.Lifetime = ServiceLifetime.Transient; // This will register the services with a Transient lifetime.
        });

        builder.Services.AddAuthorization(options =>
        {
            options.AddDefaultSecurityOptions();

            // Here you can add additional authorization policies
        });

        var app = builder.Build();
        await RegisterServicesExtensions.ConfigureDatabaseAsync(app.Services);

        app.UseHttpsRedirection();
        app.UseStatusCodePages();

        app.UseMiddleware<MinimalApiExceptionMiddleware>();

        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", $"{app.Environment.ApplicationName} v1");
            });
        }

        app.UseRouting();
        app.UseCors("cors");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseMapEndpoints(featureFlagsOptions);
        await app.RunAsync();
    }
}

πŸ” Authentication

This library currently supports the following authentication types:

  • JWT Bearer Token

πŸ§‘β€πŸ’Ό Administrator Account

A default administrator account is created automatically with the following configuration:

  • Email: set via UsersOptions:AssignAdminEmail
  • Username: set via UsersOptions:AssingAdminUsername
  • Password: set via UsersOptions:AssignAdminPassword

πŸ“š API Reference

See the documentation for a list of all available endpoints.

πŸ“¦ Packages

Name Type Version
Identity.Module.API Main Nuget Package
Identity.Module.AccountManager Dependence Nuget Package
Identity.Module.AuthManager Dependence Nuget Package
Identity.Module.ClaimsManager Dependence Nuget Package
Identity.Module.Core Dependence Nuget Package
Identity.Module.EmailManager Dependence Nuget Package
Identity.Module.Licenses Dependence Nuget Package
Identity.Module.ModuleManager Dependence Nuget Package
Identity.Module.PolicyManager Dependence Nuget Package
Identity.Module.ProfileManager Dependence Nuget Package
Identity.Module.RolesManager Dependence Nuget Package
Identity.Module.Shared Dependence Nuget Package

πŸ† Badges

SonarCloud

Quality Gate Status Bugs Code Smells Duplicated Lines (%) Lines of Code

Reliability Rating Security Rating Technical Debt Maintainability Rating Vulnerabilities

πŸ—ΊοΈ Roadmap

  • Move the configuration of the claims to a dedicated library
  • Move the configuration of the module to a dedicated library
  • Move the configuration of the roles to a dedicated library
  • Add CancellationToken to API endpoints (where necessary)
  • Replacing exceptions with implementation of operation results
  • Add centralized logging with Serilog
  • Fix the TODOs
  • Migrate SmtpOptions configuration to database
  • Migrate FeatureFlagsOptions configuration to database
  • Replacing the hosted service email sender using Coravel jobs
  • Add endpoints for two-factor authentication and management
  • Add endpoints for downloading and deleting personal data
  • Code Review and Refactoring

Future implementations

  • Add support for the MySQL database
  • Add support for the PostgreSQL database
  • Add support for the SQLite database
  • Add support for the AzureSQL database
  • Add support for multi tenancy
  • Add authentication support from third-party providers (e.g. Auth0, KeyCloak, GitHub, Azure)
  • Migrate your repository to .NET 10
  • Change the entity ID type from INT to GUID

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

⭐ Give a Star

Don't forget that if you find this project helpful, please give it a ⭐ on GitHub to show your support and help others discover it.

🀝 Contributing

The project is constantly evolving. Contributions are always welcome. Feel free to report issues and submit pull requests to the repository, following the steps below:

  1. Fork the repository
  2. Create a feature branch (starting from the develop branch)
  3. Make your changes
  4. Submit a pull requests (targeting develop)

πŸ†˜ Support

If you have any questions or need help, read here to find out what to do.

About

A set of libraries to easily integrate and extend authentication in ASP.NET Core projects, using ASP.NET Core Identity.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages