ApiFeatures.Authentications.Users.Databases.Postgres 10.0.0

dotnet add package ApiFeatures.Authentications.Users.Databases.Postgres --version 10.0.0
                    
NuGet\Install-Package ApiFeatures.Authentications.Users.Databases.Postgres -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.Postgres" 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.Postgres" Version="10.0.0" />
                    
Directory.Packages.props
<PackageReference Include="ApiFeatures.Authentications.Users.Databases.Postgres" />
                    
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.Postgres --version 10.0.0
                    
#r "nuget: ApiFeatures.Authentications.Users.Databases.Postgres, 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.Postgres@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.Postgres&version=10.0.0
                    
Install as a Cake Addin
#tool nuget:?package=ApiFeatures.Authentications.Users.Databases.Postgres&version=10.0.0
                    
Install as a Cake Tool

ApiFeatures.Authentications.Users.Databases.Postgres

PostgreSQL storage of the iot-vn Authentication Service Users module (F22). It implements the three ApiFeatures.Authentications.Users.Cores storage interfaces (IUserDatabaseService, IPasswordResetRequestDatabaseService, IUsersDatabaseInitializationService) and ships the EF Core migrations of the users tables. The sessions table and its migrations belong to the host (see the root README). Targets net9.0;net10.0 (EF Core 9.0 / Npgsql.EF 9.0 on both).

Package

Published on nuget.org as ApiFeatures.Authentications.Users.Databases.Postgres (MIT license, symbols and Source Link). It depends on ApiFeatures.Authentications.Users.Cores (>= 10.0.0) and brings EF Core 9.0 and Npgsql.EF 9.0; the EF Core migrations of the users tables are compiled into the assembly. Microsoft.EntityFrameworkCore.Design is a build-time reference only and is not a package dependency. 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.Postgres" Version="10.0.0" />

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

Register exactly one Users database library (this one or ...Databases.Mongo):

services.AddUsersPostgresDatabase(new PostgresqlDatabaseOptions
{
    Host = "localhost", Port = 5432, Username = "authentication", Password = "...",
    DatabaseName = "authentication", Schema = "auth"
}, new UsersPostgresDatabaseOptions { ApplyMigrationsOnStartup = false });

Configuration in the service

Database__Type=Postgresql selects this library. PostgreSQL is configured only through the Database section (there is no connection-string form), and ConnectionStrings__Authentication must not be set at the same time.

Variable Required Default Purpose
Database__Type yes Mongo Postgresql
Database__Host no localhost server host
Database__Port no 5432 1-65535
Database__Username in practice none database user (needs Database__Password)
Database__Password with the user none secret, never logged
Database__UseTls no false true sets SslMode=Require
Database__DatabaseName yes none database name
Database__Schema no none (public) schema of every table and both history tables; lowercase identifier ^[a-z_][a-z0-9_]{0,62}$
Database__ApplyMigrationsOnStartup no false true: create the schema (when set) and apply the shipped migrations at startup

With the opt-in off (default) and migrations pending, the service refuses to start: "The PostgreSQL schema is not up to date: N pending migration(s) (...)". If PostgreSQL is unreachable, startup fails with the Npgsql message (never the password).

Running against a local PostgreSQL container

No compose file is added to the repository.

docker run -d --name auth-pg -e POSTGRES_PASSWORD=<pw> -e POSTGRES_DB=authentication -p 5432:5432 postgres:17-alpine
# the service:
Database__Type=Postgresql Database__Host=localhost Database__Username=postgres Database__Password=<pw> \
Database__DatabaseName=authentication Database__Schema=auth Database__ApplyMigrationsOnStartup=true

Migrations

One context, one migration set, one history table (in the schema of the tables):

Context Folder History table
UsersPostgresDatabaseContext (Users, PasswordResetRequests) Migrations/Users __UsersMigrationsHistory

The sessions table and its migrations belong to the host (see the root README).

The users migrations run at startup only with Database__ApplyMigrationsOnStartup=true (the host then applies its session migrations as well). They can also be applied with the EF tooling, using the same Database__* environment variables as the service (the design-time factories read them; no value gives the DataMagic defaults, database authentication). With a schema, create it first (CREATE SCHEMA auth;).

cd src/modules/authentication/users/databases/ApiFeatures.Authentications.Users.Databases.Postgres
export Database__Host=localhost Database__Username=postgres Database__Password=<pw> Database__DatabaseName=authentication Database__Schema=auth
dotnet ef database update --context UsersPostgresDatabaseContext --framework net10.0

Adding a migration after a model change (generated files are committed as generated):

dotnet ef migrations add <Name> --context UsersPostgresDatabaseContext --output-dir Migrations/Users --framework net10.0
dotnet ef migrations has-pending-model-changes --context <Context> --framework net10.0   # must report none

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 session context, its entity options, its design-time factory and its migrations (Migrations/Sessions) moved to AuthenticationService.Apis; SessionPackageServiceKeys, PostgresTableNames.UserSessions and PostgresMigrationsHistoryTableNames.UserSessions are removed with no shim. PostgresUsersDatabaseInitializationService migrates (or checks) the users context only. The migration id, the table and the history table are unchanged (no new migration, no data migration). A host that used this library for sessions must register the session storage and its migrations itself. This change predates the first published version (10.0.0).

Schema and indexes

All tables are in Database__Schema (default public), reached through the connection's SearchPath.

Table Columns (notes)
Users Id uuid PK (never generated by the database), CreatedTime/UpdatedTime/ExpiryTime timestamptz (UTC, milliseconds), Username text, UsernameNormalized text (generated lower("Username"), stored), Email, HashedPassword, FirstName, LastName, PhotoUrl, IanaTimeZoneId, LanguageCode text, AuthenticationProvider, Status integer, Roles, AssignedFeatures text[] (order and duplicates kept; NULL and {} differ), HasEmailVerified boolean, Coordinate_Longitude, Coordinate_Latitude double precision, Coordinate_Zoom integer (all three NULL = no coordinate), RoleId uuid (the single role; NULL only before the startup migration; FK to Roles, RESTRICT)
PasswordResetRequests Id uuid PK, CreatedTime, Code, UserId uuid FK to Users (cascade), ExpiredTime
Roles Id uuid PK, Code text (unique, UPPER_SNAKE_CASE, immutable), DisplayName text, Description text NULL, IsSystem boolean, CreatedTime/UpdatedTime timestamptz
Permissions Id uuid PK, Code text (unique, UPPER_SNAKE_CASE, immutable), DisplayName text, Path text[] (parts, * only last, immutable), JoinedPath text (the parts joined with ., stored by the service, unique), Description text NULL, IsSystem boolean, CreatedTime/UpdatedTime timestamptz
RolePermissions PK (RoleId, PermissionId), CreatedTime; FK RoleId to Roles (CASCADE), FK PermissionId to Permissions (RESTRICT)
Index Serves
UX_Users_Username (unique) sign-in, get by username
UX_Users_UsernameNormalized (unique) the case-insensitive duplicate check and case-insensitive uniqueness under concurrency
IX_Users_CreatedTime_Id ORDER BY "CreatedTime", "Id" with OFFSET/LIMIT
IX_PasswordResetRequests_UserId delete by user, FK
IX_Users_RoleId_Status the startup migration (users without a role), users per role, the FK check on a role delete
UX_Roles_Code (unique) one role per code
UX_Permissions_Code, UX_Permissions_JoinedPath (unique) one permission per code and per joined path
IX_RolePermissions_PermissionId is a permission held by a role, the FK check on a permission delete

The foreign keys protect the data: a role with users cannot be deleted (FK_Users_Roles_RoleId), a permission held by a role cannot be deleted (FK_RolePermissions_Permissions_PermissionId), deleting a role deletes its links, and a user or a link cannot point to a missing row. Users.RoleId is nullable only because the legacy rule behind the first migration cannot be written in SQL; it is NOT NULL in practice once the startup migration has run.

Seeding and migration

Migration AddRolesAndPermissions only changes the schema (no data). At every start, after the migrations, the Users module runs (both steps are idempotent, use INSERT ... ON CONFLICT and are 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).
  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.

The system roles have fixed ids: ADMIN 019a8b00-0000-7000-8000-000000000001, USER 019a8b00-0000-7000-8000-000000000002.

Keyword search (ILIKE '%x%' on four columns) cannot use a B-tree; MongoDB's unanchored regular expression scans too. An optional trigram index needs CREATE EXTENSION pg_trgm (managed servers may not allow it), for example: CREATE INDEX ix_users_username_trgm ON "Users" USING gin ("Username" gin_trgm_ops); (one per searched column).

Managing roles and permissions

  • Role create is one SaveChanges (one transaction) for the role and its links; the unique index UX_Roles_Code decides a duplicate code (SQL state 23505).
  • Role update runs in one transaction that locks the role row (SELECT ... FOR UPDATE), so concurrent updates of one role are serialized (the last one wins), and replaces only the differing links.
  • Role delete is one DELETE; the links go by cascade and the foreign key FK_Users_Roles_RoleId refuses the delete when a user has the role (SQL state 23503, answered as "in use"). Permission delete is one statement that deletes the permission only when no link exists; a link added concurrently makes FK_RolePermissions_Permissions_PermissionId refuse it (also "in use").
  • Role search uses ILIKE with \ escaping and orders by Code with the "C" collation (binary order), the same order as MongoDB.
  • Wildcard and other-service permissions are ordinary rows; Path is a text[] and JoinedPath is unique.

Creating the first admin user by hand

There is no seed. Legacy MD5 bootstrap: PostgreSQL has no PBKDF2, so this SQL stores the unsalted MD5 of the ASCII password (uppercase hex; use an ASCII password), the format earlier versions used. The service still accepts it and upgrades it to the new hash at the first successful sign-in. Insert the first admin, sign in, and change the password at once:

The administrator gets the ADMIN role. The first statement creates the role when the service has not started yet (the next start links it to ALL); The administrator has full access through the ADMIN role alone (which holds ALL); no AssignedFeatures is set.

INSERT INTO "Roles" ("Id","Code","DisplayName","Description","IsSystem","CreatedTime")
VALUES ('019a8b00-0000-7000-8000-000000000001','ADMIN','Administrator','Administrators: every permission.',true,date_trunc('milliseconds', now()))
ON CONFLICT DO NOTHING;

INSERT INTO "Users" ("Id","CreatedTime","Username","HashedPassword","FirstName","LastName","AuthenticationProvider","RoleId","HasEmailVerified","Status")
VALUES (gen_random_uuid(), date_trunc('milliseconds', now()), '<username>', upper(md5('<ascii password>')), '<first>', '<last>', 0, '019a8b00-0000-7000-8000-000000000001', true, 1);

(gen_random_uuid() is built in from PostgreSQL 13. The shell history keeps the SQL: prefer a client that does not log it.) Status 1 is Active (UserStatuses: 0 Pending, 1 Active, 2 Disabled); a Pending user cannot sign in.

Until the first sign-in (or the password change) the MD5 value stays in the database. If no sign-in happens, the wrap-legacy-passwords command of the service image (repository README, section 2.5) replaces it with a slow salted hash of it, without the password.

Known differences from MongoDB

  • Usernames with .: the MongoDB duplicate check treats . as a wildcard (a.b matches axb); PostgreSQL compares lower() literally. A concurrent duplicate create gives the conflict answer on PostgreSQL (MongoDB: a 500).
  • Session table limits (the host sessions table): the sessions package stores Username in varchar(255) and the session Key in varchar(500). A username longer than 255 characters (usernames have no maximum) cannot create a session on PostgreSQL.
  • Unicode: PostgreSQL lower()/ILIKE and MongoDB's case-insensitive regex can differ for rare letters (for example ß, Turkish dotted İ); this affects the duplicate check and keyword search for such names. Case-insensitive matching of non-ASCII letters needs a UTF-8 LC_CTYPE (the official image default en_US.utf8 folds Vietnamese; a database created with the C locale folds ASCII only). Keyword search itself is the same rule on both databases since Task 25 (case-insensitive, literal, accent-sensitive).
  • Lists are ordered by CreatedTime, Id (the insertion order of users created through the API); MongoDB returns natural order.

One role per user (Task 45)

  • IUserDatabaseService gains SetRoleAsync, CountActiveByRoleIdAsync, GetByRoleIdAsync, DeleteByIdAsync and a roleId filter on SearchAsync; SetRolesAsync and the writes of Roles / AssignedFeatures in UpdateAsync are gone. IRoleDatabaseService gains GetByIdsAsync. No schema change, no migration. The index IX_Users_RoleId_Status serves the counts.
  • Foreign key. FK_Users_Roles_RoleId (restrict) refuses a user insert or a role write that names a missing role; the library reports it as RoleReferenceMissingException, which the business turns into a 400 on roleId.
  • Last active administrator. The business writes first, counts active administrators after (CountActiveByRoleIdAsync), and reverts with SetRoleAsync(..., expectedRoleId) when none is left. The Testcontainers tests demote two administrators against each other 20 times and always find an active one.
  • Known environment issue, unrelated to this change: the host does not start on PostgreSQL (TypeLoadException in the sessions package), so the access rules on PostgreSQL are tested at the storage and service level.
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 54 11/24/2026

10.0.0: first public release. PostgreSQL storage of the Users module: AddUsersPostgresDatabase (DataMagic PostgresqlDatabaseOptions) registers the user, password reset request, role and permission storage on EF Core 9 / Npgsql, and the package ships the EF Core migrations of the users tables (applied at startup only when ApplyMigrationsOnStartup is true). 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.