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
<PackageReference Include="ApiFeatures.Authentications.Users.Databases.Mongo" Version="10.0.0" />
<PackageVersion Include="ApiFeatures.Authentications.Users.Databases.Mongo" Version="10.0.0" />
<PackageReference Include="ApiFeatures.Authentications.Users.Databases.Mongo" />
paket add ApiFeatures.Authentications.Users.Databases.Mongo --version 10.0.0
#r "nuget: ApiFeatures.Authentications.Users.Databases.Mongo, 10.0.0"
#:package ApiFeatures.Authentications.Users.Databases.Mongo@10.0.0
#addin nuget:?package=ApiFeatures.Authentications.Users.Databases.Mongo&version=10.0.0
#tool nuget:?package=ApiFeatures.Authentications.Users.Databases.Mongo&version=10.0.0
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 (
Hostnot empty,Port1-65535,DatabaseNameset,PasswordandAuthenticationDatabasewhenUsernameis set) and throwsInvalidOperationException("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
Permissionsholds 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.RolesholdsCode(immutable),DisplayName,Description,IsSystem,CreatedTime,UpdatedTime. It has no permission list.RolePermissionshas one document per assignment:_id,RoleId,PermissionId,CreatedTime. The grants of a role are always read throughPermissions($lookup), so a link whose permission is gone grants nothing.Users.RoleIdis 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 toUSER(their ids are logged).- The system roles have fixed ids:
ADMIN019a8b00-0000-7000-8000-000000000001,USER019a8b00-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):
- Seed: the 17 system permissions (an existing code only gets
IsSystem = true), the rolesADMIN("Administrator", holdsALL=*only) andUSER("User", holds nothing when first created; its permissions are never reset), then the orphan sweep. - User migration, in batches of 500: a user without
RoleIdgetsADMINwhen itsAssignedFeaturescontain a pattern that grants all five legacy user permissions (*,user.*, ...) or its legacyRolescontainadminin any letter case; everyone else getsUSER. The id (only) of each user whose old direct features the new role does not fully grant is logged.RolesandAssignedFeaturesare never changed, so a rollback stays possible.
Managing roles and permissions
- Role create: the role is inserted, then its links with
InsertMany; the unique indexCode_1decides 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
USERand logs the id. There is no "being deleted" marker. PostgreSQL has no such race: the foreign keyUsers.RoleIdrefuses 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
CodeorDisplayNamewith an escaped, case-insensitive regular expression, ordered byCode,_id(binary order, i.e. ordinal).
Keyword search
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
SessionPackageServiceKeysclass andAuthenticationDatabaseCollectionNames.UserSessionsare removed with no shim. They live inAuthenticationService.Apis, which also creates theUserSessionsindexes at startup.MongoUsersDatabaseInitializationServiceno longer does nothing since Task 43: it takes anIServiceScopeFactoryand 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) withn: 0; nothing is changed and the seed never overwrites an admin. A different user that already has the usernamelinh.nguyenis rejected the same way by the uniqueUsername_1index (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.nguyenand 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-passwordscommand 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)
IUserDatabaseServicegainsSetRoleAsync(a conditional write on the current role),CountActiveByRoleIdAsync(role,StatusActive,ExpiryTimenull or later),GetByRoleIdAsync(keyset pages by id),DeleteByIdAsync(compensation only) and aroleIdfilter onSearchAsync;SetRolesAsyncand the writes ofRoles/AssignedFeaturesinUpdateAsyncare gone.IRoleDatabaseServicegainsGetByIdsAsync. 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 (
SetRoleAsyncwith the expected role). Two administrators who demote each other at once cannot both stay demoted.
| Product | Versions 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. |
-
net10.0
- ApiFeatures.Authentications.Users.Cores (>= 10.0.0)
- DataMagic.MongoDatabase (>= 9.1.0)
- FluentValidation (>= 12.1.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.11)
- MongoDB.Driver (>= 3.13.0)
-
net9.0
- ApiFeatures.Authentications.Users.Cores (>= 10.0.0)
- DataMagic.MongoDatabase (>= 9.1.0)
- FluentValidation (>= 12.1.1)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.11)
- MongoDB.Driver (>= 3.13.0)
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.