Benday.Identity.CosmosDb 3.0.0

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

Benday.Identity.CosmosDb

ASP.NET Core Identity implementation using Azure Cosmos DB as the backing store. Built on top of the Benday.CosmosDb repository pattern library.

Packages

Package Description
Benday.Identity.CosmosDb Core identity models, stores, DI registration (AddCosmosIdentity), email sender interface, configuration, and admin seeding utility
Benday.Identity.CosmosDb.UI Pre-built Razor Pages (Login, Logout, Register, ChangePassword, ForgotPassword, ResetPassword, ConfirmEmail, Admin User List/Edit), RedirectToLogin Blazor component, and AddCosmosIdentityWithUI convenience method

Features

  • Full ASP.NET Core Identity support with Cosmos DB storage
  • User management (create, update, delete, find)
  • Role-based access control
  • Claims-based authorization
  • Account lockout protection
  • Two-factor authentication (2FA) support
  • External login providers (Google, Facebook, Microsoft, etc.)
  • Phone number verification
  • Security stamp management for token invalidation
  • LINQ query support
  • One-line registration via AddCosmosIdentity() (core package)
  • Admin user seeding utility via CosmosIdentitySeeder (core package)
  • Pre-built account pages: Login, Logout, AccessDenied, Register, ChangePassword, ForgotPassword, ResetPassword, ConfirmEmail (UI package)
  • Admin pages: User List (search/paginate) and Edit User (email, lockout, roles, claims) (UI package)
  • Pluggable email sender via ICosmosIdentityEmailSender with no-op default (core + UI packages)
  • Private site support via AllowRegistration option (disables registration page)
  • Admin authorization via configurable AdminRoleName option and CosmosIdentityAdmin policy
  • RedirectToLogin Blazor component (UI package)
  • Cookie configuration via AddCosmosIdentityWithUI() (UI package)

Install the UI package (includes the core package):

dotnet add package Benday.Identity.CosmosDb.UI

Register everything in Program.cs:

using Benday.Identity.CosmosDb.UI;
using Benday.CosmosDb.Utilities;

var cosmosConfig = builder.Configuration.GetCosmosConfig();

builder.Services.AddCosmosIdentityWithUI(cosmosConfig);
builder.Services.AddRazorPages();

// ...

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

That's it. No partition key knowledge, no store registration, no cookie configuration. Login/logout pages work out of the box.

Quick Start without UI (Web API, Console, etc.)

Install the core package only:

dotnet add package Benday.Identity.CosmosDb

Register stores and Identity in Program.cs:

using Benday.Identity.CosmosDb;
using Benday.CosmosDb.Utilities;

var cosmosConfig = builder.Configuration.GetCosmosConfig();

builder.Services.AddCosmosIdentity(cosmosConfig)
    .AddDefaultTokenProviders();

This registers the Cosmos DB user/role stores and ASP.NET Core Identity, but does not configure cookies or provide login pages. Configure authentication separately as needed (e.g., JWT bearer tokens for APIs).

Container Names

By default, both AddCosmosIdentity and AddCosmosIdentityWithUI store users and roles in the container specified by your CosmosConfig (i.e., CosmosConfiguration:ContainerName from appsettings). Users and roles coexist in the same container, separated by the hierarchical partition key's discriminator value.

You can override the container names if you want separate containers:

builder.Services.AddCosmosIdentityWithUI(cosmosConfig,
    options =>
    {
        options.UsersContainerName = "MyUsers";
        options.RolesContainerName = "MyRoles";
    });

Customization

builder.Services.AddCosmosIdentityWithUI(cosmosConfig,
    options =>
    {
        options.CookieName = "MyApp.Auth";
        options.CookieExpiration = TimeSpan.FromDays(30);
    },
    identity =>
    {
        identity.Password.RequiredLength = 12;
        identity.Lockout.MaxFailedAccessAttempts = 3;
    });

All available CosmosIdentityOptions:

Option Default Description
UsersContainerName CosmosConfig.ContainerName Container for user documents
RolesContainerName CosmosConfig.ContainerName Container for role documents
CookieName "Identity.Auth" Authentication cookie name
LoginPath "/Account/Login" Login page path
LogoutPath "/Account/Logout" Logout page path
AccessDeniedPath "/Account/AccessDenied" Access denied page path
CookieExpiration 14 days Cookie expiration time
SlidingExpiration true Whether to use sliding expiration
AllowRegistration true Whether self-registration is allowed (set false for private sites)
AdminRoleName "UserAdmin" Role name required for admin pages
RequireConfirmedEmail false Whether email confirmation is required before sign-in
FromEmailAddress "" "From" address used by SmtpCosmosIdentityEmailSender

Blazor Server: RedirectToLogin

In your App.razor or route component:

<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)">
    <NotAuthorized>
        <RedirectToLogin />
    </NotAuthorized>
</AuthorizeRouteView>

Seed Admin User

In Program.cs (works with both core and UI packages):

using Benday.Identity.CosmosDb;

if (args.Contains("--seed-admin"))
{
    await CosmosIdentitySeeder.SeedAdminUserInteractive(app.Services);
    return;
}

Then run: dotnet run -- --seed-admin

Email Sender

Password reset and email confirmation require an email sender. The library ships with a no-op default (NoOpCosmosIdentityEmailSender) so everything compiles and runs out of the box, but no emails are actually sent.

Option 1: Built-in SMTP sender

The core package includes SmtpCosmosIdentityEmailSender. Register it with a configured SmtpClient and set FromEmailAddress:

// Configure SmtpClient
builder.Services.AddSingleton(new SmtpClient("smtp.yourserver.com")
{
    Port = 587,
    Credentials = new NetworkCredential("user", "password"),
    EnableSsl = true
});

// Register the SMTP sender BEFORE AddCosmosIdentityWithUI
builder.Services.AddSingleton<ICosmosIdentityEmailSender, SmtpCosmosIdentityEmailSender>();

// AddCosmosIdentityWithUI uses TryAddSingleton, so it won't overwrite yours
builder.Services.AddCosmosIdentityWithUI(cosmosConfig,
    options =>
    {
        options.FromEmailAddress = "noreply@yourapp.com";
    });

Option 2: Custom implementation

For other providers (SendGrid, Amazon SES, etc.), implement ICosmosIdentityEmailSender and register it before calling AddCosmosIdentityWithUI():

using Benday.Identity.CosmosDb;

public class SendGridEmailSender : ICosmosIdentityEmailSender
{
    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        // Your SendGrid / SES / etc. implementation here
    }
}
builder.Services.AddSingleton<ICosmosIdentityEmailSender, SendGridEmailSender>();
builder.Services.AddCosmosIdentityWithUI(cosmosConfig);

If no custom sender is registered, the no-op default is used and password reset / email confirmation flows will silently skip sending.

Admin Pages

The UI package includes admin pages for user management at /Admin/Users. These pages are protected by the CosmosIdentityAdmin authorization policy, which requires the role specified by AdminRoleName (default: "UserAdmin").

Admin features:

  • Search and paginate users
  • Edit user email
  • Lock/unlock user accounts
  • Add/remove roles
  • Add/remove claims

To grant admin access, assign the admin role to a user. The CosmosIdentitySeeder automatically assigns both the "Admin" role and your configured AdminRoleName role when seeding.

To customize the admin role name:

builder.Services.AddCosmosIdentityWithUI(cosmosConfig,
    options =>
    {
        options.AdminRoleName = "SuperAdmin";
    });

Private Sites

To disable self-registration (e.g., for internal or invite-only applications):

builder.Services.AddCosmosIdentityWithUI(cosmosConfig,
    options =>
    {
        options.AllowRegistration = false;
    });

When AllowRegistration is false, the Register page returns a 404 and the "Create an account" link is hidden from the login page.

Dependencies

  • Benday.CosmosDb - Cosmos DB repository pattern library
  • Microsoft.Extensions.Identity.Core

Implemented Interfaces

User Store (CosmosDbUserStore)

  • IUserStore<CosmosIdentityUser>
  • IUserPasswordStore<CosmosIdentityUser>
  • IUserEmailStore<CosmosIdentityUser>
  • IUserRoleStore<CosmosIdentityUser>
  • IUserSecurityStampStore<CosmosIdentityUser>
  • IUserLockoutStore<CosmosIdentityUser>
  • IUserClaimStore<CosmosIdentityUser>
  • IUserTwoFactorStore<CosmosIdentityUser>
  • IUserPhoneNumberStore<CosmosIdentityUser>
  • IUserAuthenticatorKeyStore<CosmosIdentityUser>
  • IUserTwoFactorRecoveryCodeStore<CosmosIdentityUser>
  • IUserLoginStore<CosmosIdentityUser>
  • IQueryableUserStore<CosmosIdentityUser>

Role Store (CosmosDbRoleStore)

  • IRoleStore<CosmosIdentityRole>
  • IRoleClaimStore<CosmosIdentityRole>
  • IQueryableRoleStore<CosmosIdentityRole>

Claims Principal Factory

  • DefaultUserClaimsPrincipalFactory - A default implementation that adds role claims to the identity.

Domain Models

CosmosIdentityUser

The user entity with support for:

  • Username and email (with automatic normalization)
  • Password hash
  • Security stamp and concurrency stamp
  • Phone number with confirmation
  • Two-factor authentication (authenticator key, recovery codes)
  • Account lockout
  • Claims collection
  • External login providers

CosmosIdentityRole

The role entity with support for:

  • Role name (with automatic normalization)
  • Concurrency stamp
  • Claims collection

Partition Key Strategy

All identity entities use a "SYSTEM" partition key by default, meaning all users and roles are stored in the same logical partition. This simplifies queries and works well for most applications. If you need a different partitioning strategy, you can override the SystemOwnedItem base class.

Migration from v1.x

v2.0 is a breaking change. All identity classes have been renamed to avoid namespace collisions with Microsoft.AspNetCore.Identity:

v1.x v2.0
IdentityUser CosmosIdentityUser
IdentityRole CosmosIdentityRole
IdentityConstants CosmosIdentityConstants
IdentityClaim CosmosIdentityClaim
IdentityUserClaim CosmosIdentityUserClaim
IdentityUserLogin CosmosIdentityUserLogin

Using aliases are no longer needed. You can remove any using IdentityUser = Benday.Identity.CosmosDb.IdentityUser; directives.

License

MIT License - see LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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 (1)

Showing the top 1 NuGet packages that depend on Benday.Identity.CosmosDb:

Package Downloads
Benday.Identity.CosmosDb.UI

ASP.NET Core Identity UI for Azure Cosmos DB. Provides pre-built Login/Logout/AccessDenied Razor Pages, a RedirectToLogin Blazor component, and AddCosmosIdentityWithUI() convenience method that combines core identity registration with cookie authentication. Built on top of Benday.Identity.CosmosDb.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.0 89 2/27/2026
2.1.0 123 2/9/2026
2.0.0 116 2/5/2026
1.1.0 91 2/4/2026
1.0.0-alpha 459 12/9/2025

v3.0.0 - BREAKING: Target net10.0 only (drop netstandard2.1). Added passkey (WebAuthn/FIDO2) support via IUserPasskeyStore. Passkeys enabled by default with integrated login UX.
v2.1.0 - Added ICosmosIdentityEmailSender interface, CosmosIdentityOptions (AllowRegistration, AdminRoleName, RequireConfirmedEmail), CosmosIdentitySeeder AdminRoleName support, and DI singleton registration for options
v2.0.0 - BREAKING: Renamed all identity classes with Cosmos prefix to avoid namespace collisions (IdentityUser -> CosmosIdentityUser, IdentityRole -> CosmosIdentityRole, etc.)
v1.1.0 - Update dependencies and package metadata; Changing target framework to netstandard2.1; Removing alpha tag
v1.0.0 - Initial release with full ASP.NET Core Identity store implementations for Cosmos DB