ApiFeatures.Authentications.Users.Databases.Mongo 10.0.0

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

ApiFeatures.Authentications.Users.Databases.Mongo

The MongoDB storage of the Users module. It is the only code of the service that knows MongoDB: the connection, the collections and BSON class maps, the Guid serialization, the indexes, and the implementations of the storage interfaces of ApiFeatures.Authentications.Users.Cores. The session storage belongs to the host (see the repository README).

Targets: net9.0, net10.0. It references ApiFeatures.Authentications.Users.Cores, not the Users module. It reads no configuration.

Package

Published on nuget.org as ApiFeatures.Authentications.Users.Databases.Mongo (MIT license, symbols and Source Link). It depends on ApiFeatures.Authentications.Users.Cores (>= 10.0.0) and brings MongoDB.Driver and DataMagic.MongoDatabase. The major version follows the highest .NET version the package targets (10.x for net10.0); minor versions can contain breaking changes, so pin an exact version:

<PackageReference Include="ApiFeatures.Authentications.Users" Version="10.0.0" />
<PackageReference Include="ApiFeatures.Authentications.Users.Databases.Mongo" Version="10.0.0" />

Then register it as shown below, next to AddUsersApiModule. Do not also register ApiFeatures.Authentications.Users.Databases.Postgres: a host registers exactly one Users database library.

Release notes: 10.0.0 is the first published version (the unpublished internal version was 1.0.0).

Registration

Register exactly one Users database library next to AddUsersApiModule. A second registration, or none, stops the service at startup.

// From DataMagic MongoDatabaseOptions (the "Database" section of the host)
services.AddUsersMongoDatabase(new MongoDatabaseOptions { Host = "mongo.internal", DatabaseName = "idp" });

// From a connection string (the ConnectionStrings:Authentication fallback of the host)
services.AddUsersMongoDatabase("mongodb://user:password@host:27017/idp");
  • The options overload validates them (Host not empty, Port 1-65535, DatabaseName set, Password and AuthenticationDatabase when Username is set) and throws InvalidOperationException("Invalid MongoDB database options: ..."). The messages name properties and never contain a value.
  • The connection-string overload throws a generic message for an empty or invalid string, without the driver message (it can contain the string).
  • Nothing is logged with a password or connection string.

What it registers

Service Notes
keyed scoped IMongoDatabase (DatabaseNames.Authentication) one MongoClient per scope, as before
scoped IMongoCollection<UserEntity>, IMongoCollection<PasswordResetRequestEntity> the unique index Users.Username_1 is created lazily when the collection is resolved
scoped IMongoCollection<RoleEntity>, IMongoCollection<PermissionEntity>, IMongoCollection<RolePermissionEntity> their indexes are created at startup (below)
scoped IUserDatabaseService, IPasswordResetRequestDatabaseService, IPermissionDatabaseService, IRoleDatabaseService MongoUserDatabaseService, MongoPasswordResetRequestDatabaseService, MongoPermissionDatabaseService, MongoRoleDatabaseService
singleton IUsersDatabaseInitializationService MongoUsersDatabaseInitializationService: creates the role, permission, link and user-role indexes at startup (an existing index with other options stops the startup); it also marks the registered database (the module counts it, so none or two databases are refused)

Collections and indexes

Collection Index Serves
Users Username_1 (unique, case-sensitive) sign-in, get by username
Users RoleId_1_Status_1 the startup migration (users without a role), users per role
PasswordResetRequests none
Roles Code_1 (unique) one role per code
Permissions Code_1 (unique), JoinedPath_1 (unique) one permission per code, one per joined path
RolePermissions RoleId_1_PermissionId_1 (unique), PermissionId_1 no duplicate assignment, the grants of a role, is a permission held by a role

The sessions collection (UserSessions) and its indexes belong to the host (see docs/SessionAuthentication.md). RefreshTokens and the legacy Sessions collection exist in deployed databases but nothing reads or writes them.

Roles and permissions

  • Permissions holds the catalog: Code (UPPER_SNAKE_CASE, immutable), DisplayName, Path (array of parts, * only last, immutable), JoinedPath (the parts joined with ., stored, unique), Description, IsSystem, CreatedTime, UpdatedTime. A permission is stored once and reused by every role.
  • Roles holds Code (immutable), DisplayName, Description, IsSystem, CreatedTime, UpdatedTime. It has no permission list.
  • RolePermissions has one document per assignment: _id, RoleId, PermissionId, CreatedTime. The grants of a role are always read through Permissions ($lookup), so a link whose permission is gone grants nothing.
  • Users.RoleId is the single role of the user. It is missing/null only before the startup migration. MongoDB has no foreign keys: the startup sweep (RemoveOrphansAsync) deletes the links whose role or permission no longer exists and moves the users of a missing role to USER (their ids are logged).
  • The system roles have fixed ids: ADMIN 019a8b00-0000-7000-8000-000000000001, USER 019a8b00-0000-7000-8000-000000000002 (as BSON binary subtype 3, CSharpLegacy, like every Guid in this database).

Seeding and migration

At every start, after the indexes are created and before requests are served, the Users module runs (both steps are idempotent and safe when several instances start together):

  1. Seed: the 17 system permissions (an existing code only gets IsSystem = true), the roles ADMIN ("Administrator", holds ALL = * only) and USER ("User", holds nothing when first created; its permissions are never reset), then the orphan sweep.
  2. User migration, in batches of 500: a user without RoleId gets ADMIN when its AssignedFeatures contain a pattern that grants all five legacy user permissions (*, user.*, ...) or its legacy Roles contain admin in any letter case; everyone else gets USER. The id (only) of each user whose old direct features the new role does not fully grant is logged. Roles and AssignedFeatures are never changed, so a rollback stays possible.

Managing roles and permissions

  • Role create: the role is inserted, then its links with InsertMany; the unique index Code_1 decides a duplicate code. A crash between the two writes leaves fewer links (the answer shows them; an update fixes it).
  • Role update replaces the links by "delete the links not in the new set, then upsert the links of the new set". Two concurrent updates of the same role's permissions can interleave and leave the union of both sets. Accepted: role administrators are few and trusted, and the next update converges.
  • Role delete race (accepted). The business counts the role's users, then the library deletes the role and then its links. A user assigned to the role between the count and the delete points to a missing role: its grants resolve to nothing (fail closed), and the next startup sweep moves the user to USER and logs the id. There is no "being deleted" marker. PostgreSQL has no such race: the foreign key Users.RoleId refuses the delete.
  • Permission delete. The library refuses while any link holds the permission, deletes the permission, then its links. A role update that resolved the code before the delete and inserts its link after it leaves an orphan link: it grants nothing (grants resolve through Permissions), is never shown and is removed by the sweep. A permission re-created with the same code gets a new id, so an orphan link never revives.
  • Role search matches Code or DisplayName with an escaped, case-insensitive regular expression, ordered by Code, _id (binary order, i.e. ordinal).

Keyword search is a case-insensitive, literal "contains" on Username, Email, FirstName and LastName, using the keyword as given (not trimmed; null or blank after trim returns every user), accent-sensitive, the same rule as PostgreSQL. The keyword is escaped by LiteralRegexPatterns.Escape and matched with the regex option i, so no character has a special meaning and no keyword is an invalid pattern. Changed in Task 25: before, the keyword was a raw case-sensitive regular expression (results differ for mixed-case and special-character keywords).

Behavior kept from the original code

  • The duplicate-username check is case-insensitive and unescaped; a concurrent duplicate insert is rejected by the unique index and surfaces as the driver error (500), not as a conflict answer.
  • Paging uses the DataMagic ToSearchResultAsync (always a count, natural order).

Breaking changes

  • Sessions moved to the host (Task 33). This library no longer references the sessions package and no longer registers the session storage: the keyed session database context, collection and session service, the SessionPackageServiceKeys class and AuthenticationDatabaseCollectionNames.UserSessions are removed with no shim. They live in AuthenticationService.Apis, which also creates the UserSessions indexes at startup. MongoUsersDatabaseInitializationService no longer does nothing since Task 43: it takes an IServiceScopeFactory and creates the role and permission indexes. A host that used this library for sessions must register the session storage itself. This change predates the first published version (10.0.0).

Creating the first admin user

The seed database/scripts/authentication-service/20220606003_add-users.json creates the administrator linh.nguyen (RoleId of the ADMIN role and no AssignedFeatures, authentication provider 0, email verified) as Active (Status 1; UserStatuses: 0 Pending, 1 Active, 2 Disabled). A Pending user cannot sign in. The PostgreSQL equivalent (same status, features and provider) is in the PostgreSQL library README.

The administrator has full access through the ADMIN role alone (which holds ALL): RoleId is the fixed id of ADMIN, so the first start links the role to ALL. Stored AssignedFeatures of existing users grant nothing any more.

Apply it to a new database with mongosh, before or after the first start of the service. Use the connection string of the service (ConnectionStrings__Authentication, or built from the Database__* values) with the configured database name:

mongosh "<connection string>" --eval 'EJSON.parse(fs.readFileSync("database/scripts/authentication-service/20220606003_add-users.json","utf8")).forEach(c => printjson(db.runCommand(c)))'
  • A successful run prints n: 1, ok: 1.
  • If the admin already exists (same _id), the result is a duplicate-key write error (code 11000) with n: 0; nothing is changed and the seed never overwrites an admin. A different user that already has the username linh.nguyen is rejected the same way by the unique Username_1 index (once the service has created it). Apply the seed only to a new database.
  • The seed holds the wrapped form ($pbkdf2-sha256-md5$...) of the same password it always had: the password is unchanged, and the stored value is a slow salted hash of the old MD5 value. The service upgrades it to the plain new format at the first successful sign-in.
  • Sign in with create-session as linh.nguyen and change the password right after the first sign-in (PUT api/user/{userId}/password; the new password is stored with the new hash). The seed password and its hash are not repeated in the documentation. The old MD5 value of this seed stays in git history: change the password wherever it is used.
  • A database seeded by an older version still holds the MD5 value; the service accepts it, and the wrap-legacy-passwords command of the image (repository README, section 2.5) replaces it with the wrapped form without the password.

An admin left Pending by an older seed

Earlier versions of the seed created the admin with Status 0 (Pending), so it could not sign in. Activate it by hand:

db.Users.updateOne({ Username: "linh.nguyen", Status: 0 }, { $set: { Status: 1 } })

matchedCount: 0 means the admin was already activated (or does not exist, or is Disabled): nothing changes. Sign-in works at once. Restart the service afterwards: the user cache that other services read through RabbitMQ is filled at startup, so they see the admin as Active only after a restart.

One role per user (Task 45)

  • IUserDatabaseService gains SetRoleAsync (a conditional write on the current role), CountActiveByRoleIdAsync (role, Status Active, ExpiryTime null or later), GetByRoleIdAsync (keyset pages by id), DeleteByIdAsync (compensation only) and a roleId filter on SearchAsync; SetRolesAsync and the writes of Roles / AssignedFeatures in UpdateAsync are gone. IRoleDatabaseService gains GetByIdsAsync. They use the existing indexes (RoleId_1_Status_1).
  • Delete race. MongoDB has no foreign key. A role deleted between the business check and a user write is undone by the business (it re-reads the role and puts the user back); the rest is covered by the startup sweep, which moves users of a missing role to USER. Until then such a user has no permissions (fail closed).
  • Last active administrator. The business writes first, counts active administrators after, and reverts with a conditional write when none is left (SetRoleAsync with the expected role). Two administrators who demote each other at once cannot both stay demoted.
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 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

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
10.0.0 53 11/24/2026

10.0.0: first public release. MongoDB storage of the Users module: AddUsersMongoDatabase (DataMagic MongoDatabaseOptions or a connection string) registers the user, password reset request, role and permission storage and creates the indexes at startup. Depends on ApiFeatures.Authentications.Users.Cores (>= 10.0.0). Register exactly one Users database package. Versioning: the major version is the highest .NET version targeted; minor versions can be breaking, so pin an exact version.