CerbiShield.Authentication-Shared 1.1.0

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

CerbiShield.Authentication-Shared

A lightweight, configuration-driven JWT authentication library for ASP.NET Core applications. Simplifies JWT bearer authentication setup with built-in support for Azure AD (Entra ID) and Auth0 identity providers.

Features

  • Single extension method – Configure JWT authentication with one line of code
  • Configuration-driven – All settings from appsettings.json or environment variables
  • Multi-provider support – Works with Azure AD, Auth0, and other OpenID Connect providers
  • Multi-tenant ready – Support for multiple valid issuers
  • Strongly-typed user context – Extract user information from ClaimsPrincipal into a clean model
  • Built-in diagnostics – Automatic logging of authentication events for troubleshooting
  • Startup validation – Fail fast with clear error messages if configuration is invalid

Package & Target Framework

  • Package name: CerbiShield.Authentication-Shared
  • Current version: 1.1.0
  • 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.

Dependencies

This package includes the following dependencies:

Microsoft Packages:

  • Microsoft.AspNetCore.Authentication.JwtBearer (8.0.15)
  • Microsoft.Extensions.Configuration.Abstractions (8.0.0)
  • Microsoft.Extensions.DependencyInjection.Abstractions (8.0.0)
  • Microsoft.Extensions.Logging.Abstractions (8.0.0)

IdentityModel Packages (all at 7.5.1 for consistency):

  • Microsoft.IdentityModel.JsonWebTokens (7.5.1)
  • Microsoft.IdentityModel.Tokens (7.5.1)
  • Microsoft.IdentityModel.Protocols (7.5.1)
  • Microsoft.IdentityModel.Protocols.OpenIdConnect (7.5.1)
  • System.IdentityModel.Tokens.Jwt (7.5.1)

Installation

Install the package from NuGet.org:

dotnet add package CerbiShield.Authentication-Shared

Or via Package Manager Console:

Install-Package CerbiShield.Authentication-Shared

Ensure your project targets .NET 8.0 or compatible.

Quick Start

1. Configure appsettings.json

Azure AD (Entra ID) example:

{
  "JWT": {
    "Authority": "https://login.microsoftonline.com/{your-tenant-id}/v2.0",
    "Audience": "api://{your-client-id}"
  }
}

Auth0 example:

{
  "JWT": {
    "Authority": "https://{your-domain}.auth0.com",
    "Audience": "https://your-api-identifier"
  },
  "IdentityProvider": {
    "RoleClaim": "https://your-namespace/roles",
    "ScopeClaim": "scope"
  }
}

2. Wire up authentication in Program.cs

using CerbiShield.Authentication.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Register IConfiguration (required)
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);

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

builder.Services.AddControllers();

var app = builder.Build();

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

app.MapControllers();

app.Run();

AddCerbiJwtAuthentication configures JWT bearer authentication with sensible defaults, registers the options pattern for configuration, and adds UserContextFactory for extracting user information.

Configuration Reference

JWT Settings

Key Description Default
JWT:Authority OpenID Connect authority URL Required
JWT:Audience Expected token audience Required
JWT:ValidIssuers Comma-separated list of valid issuers (multi-tenant) Authority URL
JWT:RequireHttpsMetadata Require HTTPS for metadata endpoint true
JWT:SaveToken Save token on authentication ticket false

IdentityProvider Settings

Key Description Default
IdentityProvider:RoleClaim Claim type for user roles roles
IdentityProvider:ScopeClaim Claim type for scopes scp
IdentityProvider:NameClaimType Claim type for user display name name
IdentityProvider:UserTypeClaim Claim type for user type extension_userType
IdentityProvider:AppClaim Claim type for application identifier app
IdentityProvider:FeaturesClaim Claim type for features/permissions features

Note: JWT:Authority and JWT:Audience can also be specified under IdentityProvider: as fallbacks.

User Context

The UserContextFactory service converts a ClaimsPrincipal into a strongly-typed UserContext model:

public class UserContext
{
    public string UserId { get; set; }
    public List<string> Roles { get; set; }
    public string UserType { get; set; }
    public string AccessScope { get; set; }
    public string AppName { get; set; }
    public List<string> Permissions { get; set; }
}

Usage Example

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

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

    [HttpGet("profile")]
    [Authorize]
    public IActionResult GetProfile()
    {
        var userContext = _userContextFactory.CreateFromClaimsPrincipal(User);

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

Claim Mapping

Property Claim Source Fallback Chain
UserId oidnameidentifiersub "anonymous"
Roles Configured RoleClaim Empty list
UserType Configured UserTypeClaim "guest"
AccessScope Configured ScopeClaim "default"
Permissions Configured FeaturesClaim Empty list

Permissions parsing: Supports JSON arrays (["read", "write"]) and delimited strings (read,write;delete).

Multi-Tenant Configuration

For applications accepting tokens from multiple tenants:

{
  "JWT": {
    "Authority": "https://login.microsoftonline.com/common/v2.0",
    "Audience": "api://{your-client-id}",
    "ValidIssuers": "https://login.microsoftonline.com/{tenant1}/v2.0,https://login.microsoftonline.com/{tenant2}/v2.0"
  }
}

License

MIT

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
  • Auth configuration load emits a structured info log (authority host, audience, claim mappings)
  • Authentication events log common failures and challenges (OnAuthenticationFailed, OnChallenge, OnTokenValidated)
  • Invalid JSON in feature claims logs a warning and results in no permissions extracted from that specific claim
  • Authenticated users missing the configured role claim log a warning to help diagnose misconfigured role mappings

Integration Contract

Required configuration keys

  • JWT:Authority (or IdentityProvider:Authority)
  • JWT:Audience (or IdentityProvider:Audience)

Optional configuration keys

  • JWT:ValidIssuers (comma/semicolon list)
  • IdentityProvider:RoleClaim (default "roles")
  • IdentityProvider:ScopeClaim (default "scp")
  • IdentityProvider:NameClaimType (default "name")
  • IdentityProvider:UserTypeClaim (default "extension_userType")
  • IdentityProvider:AppClaim (default "app")
  • IdentityProvider:FeaturesClaim (default "features")

Expected claims

  • Subject identifier: "oid" (Entra ID), or "sub" (OIDC standard)
  • Roles: "roles" or custom role claim configured via IdentityProvider:RoleClaim
  • Scopes: "scp" or custom scope claim configured via IdentityProvider:ScopeClaim

Setting a custom role claim type

Use IdentityProvider:RoleClaim to set the claim type containing roles. For example, Auth0 often uses a namespaced claim like "https://cerbi.io/roles".

ACA environment variables example

When deploying to Azure Container Apps, configuration keys can be provided as environment variables:

JWT__Authority=https://login.microsoftonline.com/{tenantId}/v2.0
JWT__Audience=api://your-api-client-id
JWT__ValidIssuers=https://login.microsoftonline.com/{tenantId}/v2.0
JWT__RequireHttpsMetadata=true
JWT__SaveToken=false
IdentityProvider__RoleClaim=roles
IdentityProvider__ScopeClaim=scp
IdentityProvider__NameClaimType=name

Versioning & Changelog

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.

Version History

v1.0.2 (Current)

  • Added complete IdentityModel package dependencies for consistency
  • All IdentityModel packages pinned to version 7.5.1:
    • Microsoft.IdentityModel.JsonWebTokens
    • Microsoft.IdentityModel.Tokens
    • Microsoft.IdentityModel.Protocols
    • Microsoft.IdentityModel.Protocols.OpenIdConnect
    • System.IdentityModel.Tokens.Jwt

v1.0.1

  • Initial release with core authentication functionality

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.2).

git tag v1.0.2
git push origin v1.0.2

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 496 1/30/2026
1.1.0 94 1/30/2026
1.0.2 143 1/28/2026
1.0.0 218 1/27/2026