CerbiShield.Authentication-Shared 1.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package CerbiShield.Authentication-Shared --version 1.0.2
                    
NuGet\Install-Package CerbiShield.Authentication-Shared -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="CerbiShield.Authentication-Shared" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CerbiShield.Authentication-Shared" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="CerbiShield.Authentication-Shared" />
                    
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 CerbiShield.Authentication-Shared --version 1.0.2
                    
#r "nuget: CerbiShield.Authentication-Shared, 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 CerbiShield.Authentication-Shared@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=CerbiShield.Authentication-Shared&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=CerbiShield.Authentication-Shared&version=1.0.2
                    
Install as a Cake Tool

CerbiShield.Authentication-Shared

CerbiShield.Authentication-Shared is a shared authentication library used by CerbiShield services and applications. It centralizes JWT bearer configuration, identity provider settings, and user-context extraction so that all CerbiShield components behave consistently when working with authenticated users.

This package is intended for internal CerbiShield use only and is published as a private NuGet package.

Features

  • Standardized JWT bearer authentication via a single extension method
  • Centralized, configuration-driven identity provider options
  • Strongly typed user context built from ClaimsPrincipal
  • Consistent handling of roles, scopes, user types, app identifiers, and feature/permission claims
  • Opinionated defaults for Azure AD and Auth0-based identity providers

Package & Target Framework

  • Package name: CerbiShield.Authentication.Shared (adjust to match actual NuGet ID)
  • Root namespace: CerbiShield.Authentication
  • Target framework: .NET 8.0 (net8.0)

This package is designed primarily for ASP.NET Core applications and services using JWT bearer authentication.

Installation

From your internal NuGet feed, add a reference to the package, for example:

dotnet add package CerbiShield.Authentication.Shared

Ensure your project targets .NET 8.0 or compatible.

Quick Start

Configure appsettings.json

{
  "JWT": {
    "Authority": "https://login.microsoftonline.com/{tenantId}/v2.0",
    "Audience": "api://your-api-client-id"
  },
  "IdentityProvider": {
    "Authority": "https://login.microsoftonline.com/{tenantId}/v2.0",
    "Audience": "api://your-api-client-id",
    "RoleClaim": "roles",
    "ScopeClaim": "scp",
    "UserTypeClaim": "user_type",
    "AppClaim": "app",
    "FeaturesClaim": "features"
  }
}

Wire up authentication in Program.cs

using CerbiShield.Authentication.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add CerbiShield JWT authentication
builder.Services.AddCerbiJwtAuthentication(builder.Configuration);

builder.Services.AddControllers();

var app = builder.Build();

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

app.MapControllers();

app.Run();

AddCerbiJwtAuthentication configures JwtBearerDefaults.AuthenticationScheme with authority and audience, sets token validation parameters, applies identity provider–specific behavior, registers IdentityProviderOptions, and adds UserContextFactory to DI.

Configuration Details

JWT settings

These configuration keys are read from configuration (e.g. appsettings.json, environment variables):

  • JWT:Authority – JWT/OpenID Connect authority URL (Azure AD, Auth0, etc.)
  • JWT:Audience – Expected audience for tokens

If JWT:Authority or JWT:Audience are not provided, the library falls back to:

  • IdentityProvider:Authority
  • IdentityProvider:Audience

If neither source provides non-empty values, AddCerbiJwtAuthentication throws InvalidOperationException at startup.

IdentityProvider options

IdentityProviderOptions (in CerbiShield.Authentication.Configuration) are bound from the IdentityProvider section.

Common keys:

  • IdentityProvider:Authority – Default authority if JWT:Authority is not set
  • IdentityProvider:Audience – Default audience if JWT:Audience is not set
  • IdentityProvider:RoleClaim – Claim type for roles (defaults to "roles" if missing/empty)
  • IdentityProvider:ScopeClaim – Claim type for scopes (defaults to "scp" if missing/empty)
  • IdentityProvider:UserTypeClaim – Claim for user type
  • IdentityProvider:AppClaim – Claim for application/client identifier
  • IdentityProvider:FeaturesClaim – Claim(s) describing enabled features/permissions

The library normalizes RoleClaim and ScopeClaim so they always have valid values (roles / scp).

Authentication Behavior

AddCerbiJwtAuthentication

Namespace: CerbiShield.Authentication.Extensions

public static class CerbiAuthenticationExtensions
{
    public static IServiceCollection AddCerbiJwtAuthentication(
        this IServiceCollection services,
        IConfiguration configuration);
}

Behavior:

  • Reads JWT:Authority and JWT:Audience
  • Normalizes identity provider claims (RoleClaim, ScopeClaim)
  • Detects Auth0 when the authority contains "auth0.com" and sets TokenValidationParameters.ValidIssuer accordingly
  • Configures:
    • ValidateIssuer = true
    • ValidateAudience = true
    • ValidateLifetime = true
    • ValidateIssuerSigningKey = true
    • RoleClaimType based on RoleClaim (default "roles")
    • NameClaimType = "name"
  • Registers IdentityProviderOptions from configuration
  • Registers logging and UserContextFactory as scoped services

User Context

UserContextFactory

Namespace: CerbiShield.Authentication.Services

public class UserContextFactory
{
    public UserContextFactory(
        IOptions<IdentityProviderOptions> options,
        ILogger<UserContextFactory> logger);

    public UserContext CreateFromClaimsPrincipal(ClaimsPrincipal user);
}

UserContextFactory converts a ClaimsPrincipal into a strongly typed UserContext model. It centralizes the mapping of claims to roles, permissions, scopes, and other user details.

Mapping behavior
  • UserId – from ClaimTypes.NameIdentifier, then "sub", else "anonymous"
  • Roles – from claims of type IdentityProviderOptions.RoleClaim (default "roles"), allowing multiple claims and delimited values (, and ;), de-duplicated case-insensitively
  • UserType – from IdentityProviderOptions.UserTypeClaim, default "guest" if missing
  • AccessScope – from IdentityProviderOptions.ScopeClaim (default "scp"), default "default" if missing
  • AppName – from IdentityProviderOptions.AppClaim, or empty string if missing
  • Permissions – from IdentityProviderOptions.FeaturesClaim:
    • Supports JSON arrays: e.g. "[\"feature1\", \"feature2\"]"
    • Supports delimited strings: e.g. "feature1,feature2;feature3"
    • Trims whitespace, removes duplicates (case-insensitive)
    • On invalid JSON, logs a warning and returns no permissions for that claim

Typical Usage in CerbiShield Services

Inject UserContextFactory and use it wherever you need user information derived from JWT claims:

using CerbiShield.Authentication.Services;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ExampleController : ControllerBase
{
    private readonly UserContextFactory _userContextFactory;

    public ExampleController(UserContextFactory userContextFactory)
    {
        _userContextFactory = userContextFactory;
    }

    [HttpGet("me")]
    public IActionResult GetMe()
    {
        var userContext = _userContextFactory.CreateFromClaimsPrincipal(User);

        return Ok(new
        {
            userContext.UserId,
            userContext.Roles,
            userContext.UserType,
            userContext.AccessScope,
            userContext.AppName,
            userContext.Permissions
        });
    }
}

All CerbiShield APIs should:

  • Call services.AddCerbiJwtAuthentication(configuration) at startup
  • Inject UserContextFactory where needed
  • Avoid manually parsing JWT claims for roles/permissions; use UserContext instead

Identity Providers

Azure AD

Typical configuration:

  • Authority: https://login.microsoftonline.com/{tenantId}/v2.0
  • Audience: api://{client-id} or a custom app ID URI

Defaults:

  • RoleClaim = "roles"
  • ScopeClaim = "scp"

Auth0

Typical configuration:

  • Authority: https://{your-domain}.us.auth0.com
  • Audience: https://cerbi.api
  • Role claim often a namespaced value like "https://cerbi.io/roles"

The library detects Auth0 by checking if the authority contains "auth0.com" and sets ValidIssuer accordingly.

Error Handling & Logging

  • Missing or empty JWT:Authority/JWT:Audience (and their fallbacks) cause InvalidOperationException at startup
  • Invalid JSON in feature claims logs a warning and results in no permissions extracted from that specific claim

Versioning & Internal Usage

This library is a shared foundation for CerbiShield services. Changes to public types such as UserContext, IdentityProviderOptions, or UserContextFactory, or to claim mapping behavior should be treated as breaking for downstream services and versioned accordingly.

Coordinate changes with teams consuming this package and maintain backward-compatible configuration keys where possible.

Publishing (NuGet)

This repository is configured to publish the NuGet package via GitHub Actions.

Prerequisites

  • Create a NuGet.org API key with permission to push the package.
  • Add it to the GitHub repository secrets as NUGET_API_KEY.

Release flow

Publishing runs on pushes of version tags matching v* (for example, v1.0.0).

git tag v1.0.0
git push origin v1.0.0

The workflow will:

  • Restore and build in Release mode
  • Pack CerbiShield.Authentication.csproj
  • Push the produced .nupkg to NuGet.org (skipping duplicates)
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  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.0 291 1/30/2026
1.1.0 56 1/30/2026
1.0.2 106 1/28/2026
1.0.0 181 1/27/2026