Omnia.AuthorizationUtility 1.2.1

dotnet add package Omnia.AuthorizationUtility --version 1.2.1
                    
NuGet\Install-Package Omnia.AuthorizationUtility -Version 1.2.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="Omnia.AuthorizationUtility" Version="1.2.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Omnia.AuthorizationUtility" Version="1.2.1" />
                    
Directory.Packages.props
<PackageReference Include="Omnia.AuthorizationUtility" />
                    
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 Omnia.AuthorizationUtility --version 1.2.1
                    
#r "nuget: Omnia.AuthorizationUtility, 1.2.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 Omnia.AuthorizationUtility@1.2.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=Omnia.AuthorizationUtility&version=1.2.1
                    
Install as a Cake Addin
#tool nuget:?package=Omnia.AuthorizationUtility&version=1.2.1
                    
Install as a Cake Tool

Omnia Authorization Utility

Una libreria completa per l'autenticazione e autorizzazione in applicazioni ASP.NET Core, che integra Keycloak per l'autenticazione JWT e DbAuth per autorizzazioni granulari basate su database.

🎯 Caratteristiche Principali

Autenticazione Keycloak

  • Validazione Token JWT con supporto per introspection
  • Integrazione ASP.NET Core con middleware personalizzato
  • Cache intelligente per ottimizzare le performance
  • Gestione ruoli e scope da Keycloak
  • Configurazione flessibile per diversi ambienti

Autorizzazione DbAuth

  • Autorizzazioni basate su ruoli (Role-Based Access Control)
  • Autorizzazioni basate su relazioni (Relation-Based Access Control)
  • Cache integrata per performance ottimali
  • Interfacce estensibili per implementazioni personalizzate
  • Configurazione avanzata con opzioni multiple

📦 Installazione

Prerequisiti

  • .NET 8.0 o superiore
  • ASP.NET Core
  • Keycloak Server (per autenticazione)
  • Database (per autorizzazioni DbAuth)

Pacchetti NuGet

<PackageReference Include="Omnia.AuthorizationUtility" Version="1.0.0" />
<PackageReference Include="Omnia.DbAuthInterface" Version="1.0.0" />

🚀 Configurazione Rapida

1. Startup/Program.cs

using AuthorizationUtility.Keycloak;
using AuthorizationUtility.DbAuth;

var builder = WebApplication.CreateBuilder(args);

// Configurazione Keycloak
builder.Services.AddKeycloakAuthentication(options =>
{
    options.AuthServerUrl = "https://your-keycloak.com";
    options.Realm = "your-realm";
    options.ClientId = "your-client";
    options.ClientSecret = "your-secret";
    options.RequireHttps = true;
    options.ValidateToken = true;
    options.EnableIntrospection = true;
});

// Configurazione DbAuth
builder.Services.AddDbAuth(options =>
{
    options.CacheExpirationMinutes = 15;
    options.EnableAuthorizationLogging = true;
    options.DefaultRole = "viewer";
    options.EnableStrictRoleValidation = true;
});

// Servizi aggiuntivi
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();

var app = builder.Build();

// Pipeline
app.UseAuthentication();
app.UseAuthorization();

2. Controller con Autorizzazione

[ApiController]
[Route("api/[controller]")]
[Authorize] // Richiede autenticazione Keycloak
public class DocumentsController : ControllerBase
{
    private readonly IDbAuth _dbAuth;
    private readonly ICurrentUserService _currentUser;

    public DocumentsController(IDbAuth dbAuth, ICurrentUserService currentUser)
    {
        _dbAuth = dbAuth;
        _currentUser = currentUser;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetDocument(string id)
    {
        // Verifica autorizzazione specifica per la risorsa
        var isAuthorized = await _dbAuth.IsAuthorizedAsync(
            _currentUser.UserId, 
            id, 
            "read"
        );

        if (!isAuthorized)
            return Forbid();

        // Logica per ottenere il documento
        return Ok();
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateDocument(string id)
    {
        var canEdit = await _dbAuth.IsAuthorizedAsync(
            _currentUser.UserId, 
            id, 
            "update"
        );

        if (!canEdit)
            return Forbid();

        // Logica per aggiornare il documento
        return Ok();
    }

    [HttpGet("my-permissions/{resourceId}")]
    public async Task<IActionResult> GetMyPermissions(string resourceId)
    {
        var permissions = await _dbAuth.GetUserPermissionsAsync(
            _currentUser.UserId, 
            resourceId
        );

        return Ok(permissions);
    }
}

🔧 Configurazione Avanzata

Keycloak Options

builder.Services.AddKeycloakAuthentication(options =>
{
    // Configurazione server
    options.AuthServerUrl = "https://keycloak.example.com";
    options.Realm = "my-realm";
    options.ClientId = "backend-client";
    options.ClientSecret = "secret-key";
    
    // Sicurezza
    options.RequireHttps = true;
    options.ValidateToken = true;
    options.ValidateAudience = true;
    options.ValidateIssuer = true;
    
    // Performance
    options.EnableIntrospection = true;
    options.CacheDuration = TimeSpan.FromMinutes(10);
    options.EnableTokenCache = true;
    
    // Logging
    options.EnableDetailedErrors = true;
    options.LogLevel = LogLevel.Information;
});

DbAuth Options

builder.Services.AddDbAuth(options =>
{
    // Cache
    options.CacheExpirationMinutes = 20;
    options.EnableCaching = true;
    
    // Autorizzazioni
    options.DefaultRole = "viewer";
    options.EnableStrictRoleValidation = true;
    options.EnableStrictRelationValidation = true;
    
    // Limiti
    options.MaxRolesPerUser = 15;
    options.MaxRelationsPerResource = 100;
    options.DatabaseTimeoutSeconds = 30;
    
    // Logging
    options.EnableAuthorizationLogging = true;
    
    // Pattern cache personalizzati
    options.CacheKeyPattern = "myapp:{type}:{key}";
});

💡 Esempi di Utilizzo

Verifica Ruoli

public class UserService
{
    private readonly IRoleBasedAuth _roleAuth;

    public async Task<bool> IsUserAdmin(string userId)
    {
        return await _roleAuth.HasRoleAsync(userId, "admin");
    }

    public async Task<IEnumerable<string>> GetUserRoles(string userId)
    {
        return await _roleAuth.GetUserRolesAsync(userId);
    }

    public async Task<bool> CanUserCreateDocuments(string userId)
    {
        return await _roleAuth.HasRoleAccessAsync(userId, "create");
    }
}

Gestione Relazioni

public class ResourceService
{
    private readonly IRelationBasedAuth _relationAuth;

    public async Task<bool> IsResourceOwner(string userId, string resourceId)
    {
        return await _relationAuth.HasRelationAsync(userId, resourceId, "owner");
    }

    public async Task<IEnumerable<string>> GetUserDocuments(string userId)
    {
        return await _relationAuth.GetAccessibleResourcesAsync(userId, "read");
    }

    public async Task<IEnumerable<string>> GetResourcePermissions(string userId, string resourceId)
    {
        return await _relationAuth.GetRelationPermissionsAsync(userId, resourceId);
    }
}

Informazioni Utente Corrente

public class ProfileController : ControllerBase
{
    private readonly ICurrentUserService _currentUser;

    public ProfileController(ICurrentUserService currentUser)
    {
        _currentUser = currentUser;
    }

    [HttpGet("me")]
    public IActionResult GetProfile()
    {
        if (!_currentUser.IsAuthenticated)
            return Unauthorized();

        return Ok(new
        {
            UserId = _currentUser.UserId,
            Username = _currentUser.Username,
            Email = _currentUser.Email,
            FirstName = _currentUser.FirstName,
            LastName = _currentUser.LastName,
            Scopes = _currentUser.Scopes,
            ClientId = _currentUser.ClientId
        });
    }

    [HttpGet("scopes")]
    public IActionResult GetScopes()
    {
        return Ok(_currentUser.Scopes);
    }

    [HttpGet("claims")]
    public IActionResult GetClaims()
    {
        return Ok(_currentUser.AllClaims.Select(c => new 
        { 
            Type = c.Type, 
            Value = c.Value 
        }));
    }
}

🔒 Architettura della Sicurezza

Flusso di Autenticazione

  1. Client invia token JWT da Keycloak
  2. Middleware Keycloak valida il token
  3. Claims vengono estratti e memorizzati
  4. CurrentUserService fornisce accesso alle informazioni utente

Flusso di Autorizzazione

  1. Controller riceve richiesta autenticata
  2. DbAuth verifica autorizzazioni specifiche
  3. RoleBasedAuth controlla ruoli utente
  4. RelationBasedAuth verifica relazioni risorsa-utente
  5. Cache ottimizza performance successive

Livelli di Sicurezza

  • Livello 1: Autenticazione JWT (Keycloak)
  • Livello 2: Autorizzazione basata su ruoli
  • Livello 3: Autorizzazione basata su relazioni
  • Livello 4: Autorizzazioni specifiche per risorsa

📊 Performance e Cache

Sistema di Cache Integrato

  • Cache in memoria per autorizzazioni frequenti
  • Scadenza configurabile per bilanciare performance e sicurezza
  • Invalidazione intelligente quando i permessi cambiano
  • Pattern di cache personalizzabili

Ottimizzazioni

// Cache delle autorizzazioni per 15 minuti
await _dbAuth.IsAuthorizedAsync(userId, resourceId, "read");

// Invalidazione cache utente quando cambiano i ruoli
await _authCache.InvalidateUserCacheAsync(userId);

// Batch di verifiche per performance
var permissions = await _dbAuth.GetUserPermissionsAsync(userId);

🚨 Gestione Errori

Fallback di Sicurezza

  • Errori di validazione → Accesso negato
  • Problemi di cache → Verifica diretta su database
  • Timeout database → Sicurezza first

Logging

// Abilita logging dettagliato
builder.Services.Configure<KeycloakOptions>(options =>
{
    options.EnableDetailedErrors = true;
    options.LogLevel = LogLevel.Debug;
});

🔄 Migrazione e Compatibilità

Da Versioni Precedenti

La libreria mantiene compatibilità retroattiva attraverso:

  • Interface legacy marcate con [Obsolete]
  • Extension methods per facilità di migrazione
  • Configurazioni di default sicure

Nuovi Progetti

Per nuovi progetti, utilizzare direttamente:

  • IDbAuth da DbAuthInterface
  • IKeycloakTokenValidator da AuthorizationUtility.Keycloak
  • Pattern async/await per tutte le operazioni

📚 Esempi Completi

Vedi ExampleProgram.cs per un esempio completo di integrazione che mostra:

  • Configurazione completa di entrambe le librerie
  • Utilizzo pratico nei controller
  • Gestione degli errori
  • Pattern di utilizzo consigliati

🤝 Contribuire

  1. Fork del repository
  2. Crea un branch per la feature
  3. Implementa e testa
  4. Crea Pull Request

📄 Licenza

LGPL-3.0-or-later - Vedi file LICENSE per dettagli.

👨‍💻 Autore

Luca Gualandi - Libreria di autorizzazione per ecosistema applicativo


Per supporto tecnico o domande, apri un issue su GitHub.

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
1.2.1 375 11/17/2025
1.2.0 337 11/17/2025
1.1.1 311 11/17/2025
1.1.0 292 11/13/2025
1.0.1 283 11/12/2025
1.0.0 289 11/12/2025