Nera.Lib.Authorization 1.0.2

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

Nera.Lib.Authorization

Unified authorization library for Nera applications providing:

  • AuthContext - Unified authentication context (replaces 4 different versions)
  • Authorization Handlers - Standard handlers for role/permission-based auth
  • Authorization Attributes - Convenient attributes like [RequireOrgAdmin]
  • Multi-tenant Support - Organization resolution from JWT, headers, domain
  • Token Services - JWT generation, refresh, and multi-session support
  • Token Caching - Whitelist token caching with Redis/Memory support

Installation

<PackageReference Include="Nera.Lib.Authorization" Version="1.0.0"/>

Quick Start

1. Register Services

// In Program.cs or Startup.cs
services.AddNeraAuthorization();
services.AddNeraJwtAuthentication();
services.AddNeraTokenServices();  // For token generation with multi-session support
services.AddNeraAuthorizationPolicies(options =>
{
    // Add custom permission policies
    options.AddPermissionPolicies(
        "user:create",
        "user:read",
        "user:update",
        "user:delete"
    );
});

2. Use in Controllers

[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
    private readonly ICurrentUserContext _currentUser;
    
    public UsersController(ICurrentUserContext currentUser)
    {
        _currentUser = currentUser;
    }
    
    [HttpGet]
    [RequireOrgMember]
    public async Task<IActionResult> GetUsers()
    {
        var orgId = _currentUser.OrganizationId;
        // Filter by organization...
    }
    
    [HttpPost]
    [RequirePermission("user:create")]
    public async Task<IActionResult> CreateUser(CreateUserDto dto)
    {
        // Only users with user:create permission
    }
    
    [HttpPut("{id}")]
    [RequireSameUserOrAdmin]
    public async Task<IActionResult> UpdateUser(Guid id, UpdateUserDto dto)
    {
        // User can only update their own profile, unless OrgAdmin
    }
}

3. Manual Permission Checks

public class UserService
{
    private readonly ICurrentUserContext _currentUser;
    
    public async Task DeleteUserAsync(Guid userId)
    {
        if (!_currentUser.HasPermission("user:delete"))
            throw new ForbiddenException("Missing permission: user:delete");
            
        // Delete user...
    }
}

Components

Constants

  • NeraClaimTypes - Standard JWT claim types
  • OrgRoleType - Organization role enum (Guest, User, Member, Admin, Owner)
  • NeraPolicies - Standard policy names

Interfaces

  • ICurrentUserContext - Access current user info, permissions, roles
  • IOrganizationResolver - Resolve OrgId from various sources
  • IOrganizationCacheService - Cache org domain mappings

Attributes

Attribute Description
[RequireOrgOwner] Only organization owner
[RequireOrgAdmin] Owner or Admin
[RequireOrgMember] Owner, Admin, or Member
[RequireOrgUser] Any authenticated user in org
[RequirePermission("code")] Specific permission
[RequireSameUserOrAdmin] Own data or OrgAdmin

Migration from Legacy AuthContext

Before (scattered implementations)

// 4 different AuthContext classes:
// - Nera.Lib.Core.Security.AuthContext
// - Nera.Lib.Core.Common.Models.AuthContext
// - Nera.Lib.Database.Common.AuthContext
// - Iam.Application.Common.AuthContext

After (unified)

// Single implementation:
using Nera.Lib.Authorization.Context;
using Nera.Lib.Authorization.Abstractions;

// Register once
services.AddNeraAuthorization();

// Inject anywhere
public class MyService(ICurrentUserContext currentUser)
{
    public Guid OrgId => currentUser.OrganizationId;
    public bool IsAdmin => currentUser.IsOrgAdmin;
}

Multi-tenant Organization Resolution

The AuthContext resolves organization ID in this order:

  1. JWT Claims - org_id claim from access token
  2. X-Organization-Id Header - Explicit header
  3. Origin Header - Domain lookup via IOrganizationCacheService

For login flows (before JWT exists), use explicit resolution:

public async Task<LoginResponse> Login(LoginRequest request)
{
    var orgId = await _orgResolver.ResolveOrgIdFromOriginAsync();
    // Use orgId for multi-tenant login
}

Token Services (Multi-Session Support)

The library provides reusable token generation and caching services that support:

  • Multi-session login - One user can login from multiple devices simultaneously
  • Whitelist token caching - Tokens are cached for validation
  • Refresh token rotation - Secure token refresh with session tracking

Token Cache Keys

Key Pattern Description
white_list_cache_key:{userId}:{sessionId} Session-specific token
white_list_cache_key:{userId} Backward compatible single-session
refreshToken:{token} Maps refresh token → userId:sessionId
user_sessions:{userId} List of active session IDs

Using IAuthTokenService

public class AuthService : AuthTokenService, IAuthService
{
    public AuthService(
        IJwtService jwtService,
        ITokenCacheService cacheService,
        ILogger<AuthService> logger) 
        : base(jwtService, cacheService, logger)
    {
    }

    // Your custom token generation for specific User entity
    public UserProviderToken GenerateToken(User user, string? ipAddress = null)
    {
        var request = new GenerateTokenRequest
        {
            UserId = user.Id,
            OrganizationId = user.OrgId,
            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,
            Roles = user.Roles.Select(r => r.Code).ToList(),
            IpAddress = ipAddress
        };

        return base.GenerateToken(request);
    }
}

Token Refresh

// Refresh token - automatically handles session rotation
var newToken = await _authService.RefreshTokenAsync(refreshToken);

Session Management

// Get all active sessions for a user
var sessions = _authService.GetUserActiveSessions(userId);

// Revoke a specific session (logout from one device)
_authService.RevokeSession(userId, sessionId);

// Revoke all sessions (logout from all devices)
_authService.RevokeAllUserSessions(userId);

⚠️ CRITICAL: Cache Key Normalization

All cache operations MUST use normaliseKey: false to ensure consistent key format:

// ✅ CORRECT
CachingService.Instance.PushToCache(key, value, expiry, normaliseKey: false);
CachingService.Instance.GetCacheObject<T>(key, normaliseKey: false);

// ❌ WRONG - Will cause key mismatch!
CachingService.Instance.PushToCache(key, value, expiry);  // normaliseKey defaults to false
CachingService.Instance.GetCacheObject<T>(key);            // normaliseKey defaults to true!

The TokenCacheService handles this automatically for you.

DI Registration Example

// Identity.Infrastructure/DependencyInjection.cs
public static void AddInfrastructureServices(this IServiceCollection services)
{
    // Token services from Nera.Lib.Authorization
    services.AddSingleton<ITokenCacheService, TokenCacheService>();
    services.AddScoped<IJwtService, JwtService>();
    services.AddScoped<IAuthService, AuthService>();
    
    // Other services...
}
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 (2)

Showing the top 2 NuGet packages that depend on Nera.Lib.Authorization:

Package Downloads
Nera.Lib.Web

Web models, business rules, aggregates, value objects, and domain services for Nera applications

Nera.Lib.Database

Database access layer with Entity Framework Core, Repository pattern, Specification pattern, and advanced querying capabilities for Nera applications

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 146 1/5/2026
1.0.1 77 1/5/2026
1.0.0 135 1/4/2026