ApiFeatures.Authentications.Users
10.0.0
dotnet add package ApiFeatures.Authentications.Users --version 10.0.0
NuGet\Install-Package ApiFeatures.Authentications.Users -Version 10.0.0
<PackageReference Include="ApiFeatures.Authentications.Users" Version="10.0.0" />
<PackageVersion Include="ApiFeatures.Authentications.Users" Version="10.0.0" />
<PackageReference Include="ApiFeatures.Authentications.Users" />
paket add ApiFeatures.Authentications.Users --version 10.0.0
#r "nuget: ApiFeatures.Authentications.Users, 10.0.0"
#:package ApiFeatures.Authentications.Users@10.0.0
#addin nuget:?package=ApiFeatures.Authentications.Users&version=10.0.0
#tool nuget:?package=ApiFeatures.Authentications.Users&version=10.0.0
ApiFeatures.Authentications.Users
The Users module of the iot-vn Authentication Service. It serves the 11 endpoints of the module (api/authentication/registration, api/authentication/role-assignment, api/user/..., api/time-zones), the signed-in-user authorization policy, the startup check that every endpoint has its access rule, the MassTransit consumers (GetUserById, GetUserBySessionKey, GetUserByUsername, GetUsersByIds), event publishing, the user cache, reCAPTCHA, photo upload and the hosted services.
Targets: net9.0, net10.0.
Package
Published on nuget.org as ApiFeatures.Authentications.Users (MIT license, symbols and Source Link). It depends on ApiFeatures.Authentications.Users.Cores (>= 10.0.0) and AuthenticationService.Commons (>= 10.2.0) and has a framework reference to Microsoft.AspNetCore.App. 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" />
A host that consumes the package:
- Registers exactly one Users database package (
ApiFeatures.Authentications.Users.Databases.MongoorApiFeatures.Authentications.Users.Databases.Postgres). This package does not reference either; with none or two the service refuses to start. - Must not also reference
SkiaSharp.NativeAssets.Linux. This package bringsSkiaSharp.NativeAssets.Linux.NoDependenciestransitively, and both publish alibSkiaSharp.soto the same path (see "Linux hosts").
Release notes
- 10.0.0: first published version. It contains the module as described in this README; the "Breaking changes" below describe the unpublished internal versions (1.0.0) that preceded it.
What the module does not do
- It reads no configuration. There is no
IConfigurationin the module and it defines no section names. The host reads its configuration and passesAddUsersApiModuleOptionsin. - It registers no database. The module depends on the storage interfaces of
ApiFeatures.Authentications.Users.Cores(IUserDatabaseService,IPasswordResetRequestDatabaseService,IUsersDatabaseInitializationService). The host registers exactly one Users database library (for exampleApiFeatures.Authentications.Users.Databases.Mongo). With none or two the service refuses to start. - It adds no middleware and writes no error answers. Its endpoints throw
BusinessExceptions (fromBusinessFeatures.Cores) and FluentValidationValidationExceptions; the host answers them (the Authentication Service host uses theApiFeatures.CommonsGenericExceptionMiddleware). - It does not register or serve sessions. The host registers the sessions package, its endpoints and the session schemes that the signed-in-user policy names (
AuthenticationSchemes.SessionKeyHeaderandAuthenticationSchemes.Session); without the schemes the startup tasks refuse to start. The module only offers the user-level operations that the host session code calls:IUserSignInService(the per-IP limit, reCAPTCHA and the lockout-aware credentials, in this order) andIUserPrincipalService(the claims of a user). In return the host implementsIUserSessionResolver(the username of a session key) for theGetUserBySessionKeyconsumer and gives it withWithUserSessionResolver; without it the startup tasks refuse to start.
Registration
// Program.cs of the host
services.AddImgBbService(new ImgBbOptions(apiUrl, apiKey)); // host: the ImgBB upload of BusinessFeatures.Images.ImgBbs
services.AddUsersApiModule(new AddUsersApiModuleOptions { Recaptcha = ..., ... }
.WithJsonTool(sp => sp.GetRequiredService<IJsonTool>()) // the JSON tool of the application settings (see "JSON")
.WithPhotoUploadService<ImgBbPhotoUploadService>() // any IPhotoUploadService of BusinessFeatures.Images.Abstractions
.WithUserSessionResolver<UserSessionResolver>()); // the session lookup of the GetUserBySessionKey consumer
services.AddSessionAuthenticationFeature(...); // host: the sessions package, its cache decoration and the two session schemes (the policy needs them)
services.AddApplicationSessionAuthentication(); // host: AuthenticationSchemes.SessionKeyHeader and AuthenticationSchemes.Session
services.AddApplicationJson(); // host: the IJsonSerializer and IJsonTool registrations and the HTTP JSON options (see "JSON")
services.AddUsersMongoDatabase(connectionString); // exactly one Users database library
services.AddApplicationMassTransit<Program>(configuration, x => x.AddUsersApiModuleConsumers());
services.AddOpenApi("v1", o => o.AddDocumentTransformer<ApiDocumentInfoTransformer>().AddUsersApiModuleDocument().AddApplicationJsonSchemas()); // net10.0 only; the first and last calls are the host's
var app = builder.Build();
// A host that maps its own endpoints (GET api/system/version, the session endpoints) maps them itself.
await app.RunUsersApiModuleStartupTasksAsync(); // also refuses to start when a required service was not given or a scheme of the policy is not registered
app.UseExceptionLogger();
app.UseMiddleware<...>(); // host: its error handling (for example ApiFeatures.Commons' GenericExceptionMiddleware)
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
// host: its own response middleware, if any
app.UseEndpoints(endpoints =>
{
endpoints.MapUsersApiModuleEndpoints();
endpoints.MapApplicationSystemEndpoints(); // host: the endpoints it owns, mapped on the root builder
endpoints.MapGroup(string.Empty) // host: the session endpoints, with the policy of the module
.RequireAuthorization(ApplicationAuthorizationPolicies.SignedInUser)
.AddSessionAuthenticationEndpoints();
endpoints.VerifyUsersApiModuleEndpoints(new VerifyUsersApiModuleEndpointsOptions
{
HostAnonymousEndpoints = { "GET api/system/version", "POST api/authentication/session" }, // each must be mapped once and be anonymous
HostProtectedEndpoints = { "DELETE api/authentication/session", "GET api/sessions" }, // each must carry the signed-in-user policy
HostJsonBodyEndpoints = { "POST api/authentication/session" } // the JSON body is bound by the framework
});
});
| Method | Purpose |
|---|---|
AddUsersApiModule(AddUsersApiModuleOptions) |
Services, validators, authorization (the signed-in-user policy), the sign-in and principal operations, reCAPTCHA, and the per-IP limit. It registers no authentication scheme and no session. |
AddUsersApiModuleConsumers(IBusRegistrationConfigurator) |
Adds the four consumers to the bus of the host. The GetUserBySessionKey consumer finds the session through the IUserSessionResolver given with WithUserSessionResolver. The queue names come from the consumer type names, so they did not change. |
RunUsersApiModuleStartupTasksAsync(IHost) |
Checks that a JSON serializer is registered under each key, that the JSON tool, the photo upload service and the session lookup were given (see "Services"), that the authentication schemes named by the signed-in-user policy are registered (before the database is touched), and that exactly one Users database library is registered, loads the time zones, writes the warnings (reCAPTCHA and the per-IP limit switched off), and initializes the database. |
MapUsersApiModuleEndpoints / VerifyUsersApiModuleEndpoints |
Maps the module's 11 endpoints, and refuses to start when any endpoint (module or host) breaks its access rule. Host endpoints are declared in three sets of VerifyUsersApiModuleEndpointsOptions: HostAnonymousEndpoints (mapped once and anonymous), HostProtectedEndpoints (mapped once, with the signed-in-user policy, not anonymous) and HostJsonBodyEndpoints (host endpoints, also listed in one of the two sets, whose JSON body is bound by the framework: they must accept application/json; a host endpoint not listed there must accept no body); the expected total is 11 plus the host endpoints. A missing module endpoint is named; permissions are checked inline in the endpoints and proven by scripted probes, not by this check. |
AddUsersApiModuleDocument(OpenApiOptions) |
The OpenAPI transformers of the module's endpoints (net10.0 only: the OpenAPI object model they use is in the .NET 10 package). A .NET 9 host gets the endpoints without the OpenAPI customizations. They declare the Session security scheme (kept if the host already declared one), document the request bodies of the module's endpoints, and add the session requirement only to endpoints that authorize with the module's session schemes; the document info and the endpoints of other modules are left untouched. The document info and the schema transformers for the JSON shapes of the host belong to the host. |
Roles and permissions (Task 43)
The module stores a permission catalog, roles that hold catalog permissions, and exactly one role per user. Since Task 45 access is decided by the single role of the user (see "One role per user and exact permissions" below).
- At startup (
RunUsersApiModuleStartupTasksAsync), after the database initialization and before requests,ISystemAccessSeedServiceseeds the 17 system permissions and the rolesADMIN(holdsALL) andUSER, thenIUserRoleMigrationServicegives a role to every user that has none (batches of 500, repeatable, ids only in the log). The legacy rule isILegacyAccessEvaluator(replaceable). - Every user created through the module (self-registration, admin create-user) gets the
USERrole. User answers gain one additive field,roleId. PermissionGrantSetmatches a required exact path (for exampleuser.create) against the granted paths without regular expressions:*grants everything,user.*grants everything belowuser.(segment-safe).- New services: the Users database library must register
IPermissionDatabaseServiceandIRoleDatabaseService. - No new configuration key.
Manage roles and permissions (Task 44)
The module maps nine more endpoints (20 in total, EndpointAccessRules.ApiEndpointCount): POST api/role, GET api/roles, GET|PUT|DELETE api/role/{roleId}, GET api/permissions, POST api/permission, PUT|DELETE api/permission/{permissionId}. Each handler starts with the inline check of one exact permission (role.create, role.view, role.update, role.delete, permission.view, permission.create, permission.update, permission.delete; RequiredPermissions). The business is in IRoleService and IPermissionService; role payloads reference permissions by code.
- Payloads marked
[RejectUnknownMembers](Attributes) must not carry unknown JSON members. The module has no JSON dependency: the host honours the attribute (ApplicationJsonExtensions:JsonUnmappedMemberHandling.Disallow). A host that does not honour it would silently ignore acodesent to an update. IRequestBindingServicegainsReadInt32FromQueryandReadStringFromQuery.ValidationException(FluentValidation) is used for invalid input,BusinessExceptionsubtypes for the rest (ROLE__*,PERMISSION__*).
One role per user and exact permissions (Task 45)
HttpContext.HasPermission(requiredPath, throwException)replacesHasAnyPermission: one exact required path per action (RequiredPermissions), matched against the grants of the role withPermissionGrantSet(segment-safe, no regular expression).SolidUserRequirementHandlerchecks the account state first, then reads the role and its permissions (IUserAccessService) on every request and keeps them in the request (GetUserAccess). A role that no longer exists grants nothing.- Permissions:
user.create,user.view,user.update,user.change_password,user.assign_role,role.*andpermission.*actions as in the root README.user.add,user.view_usersanduser.role_assignmentgrant nothing. IUserService.AssignRoleAsyncgives one role (own account refused, last activeADMINprotected);UpdateAsyncrefuses to disable or expire the last activeADMIN;CreateAsynctakesRoleId. A role that vanishes during a write is handled on MongoDB by compensation and on PostgreSQL by the foreign key (RoleReferenceMissingExceptionfrom the database library).IUserCacheRefreshService(andUserCacheRefreshHostedService, 30 s retry) keep the user cache in step;IUserStorageis read-through.- User answers are
UserDetailDto(no password hash, withroleId,role,permissions);CreateUserPayloadDtoandUpdateUserPayloadDtono longer acceptrolesorassignedFeatures. - Removed:
UserFeatures,PermissionUtilities(the regex matcher; onlyLegacyAccessEvaluatorkeeps the old rule, for the startup migration),AssignUserRolesCommand,HasAnyPermission, and in the CoresValidRoles,UserPermissions,IUserDatabaseService.SetRolesAsync. - Hosts need no new configuration. A Users database library must implement the new
IUserDatabaseServiceandIRoleDatabaseServicemembers (Cores 2.0.0).
Self-registration (Task 46)
AddUsersApiModuleOptions.IsRegistrationAllowed (default false, registered as IOptions<RegistrationOptions>) maps the anonymous POST api/authentication/registration. Off: the route does not exist (404, not in OpenAPI) and the startup endpoint check expects 19 endpoints (EndpointAccessRules.GetExpectedApiEndpointCount); on: 20, and a mismatch is named and refuses to start. On, IUserRegistrationService checks reCAPTCHA (captchaCode, the same IRecaptchaService as create-session), hashes the password and calls IUserService.CreateAsync with status Pending and the USER role; the answer is RegisteredUserDto. With registration on and reCAPTCHA off, the startup writes one warning.
Registration limit (Task 50). IRegistrationIpLimitService.EnsureAllowedAndCountAsync runs first in IUserRegistrationService.RegisterAsync, before reCAPTCHA, with RegisterUserCommand.ClientAddress (the connection address that the host's proxy rules already corrected). RedisRegistrationIpLimitService uses IClientIpSlidingWindowService.TryCountAsync, one atomic Redis script that drops the entries that left the window, then adds the attempt or refuses without adding. The key is USER__REGISTRATION__IP_ATTEMPTS_<bucket> (same buckets as sign-in). A refusal throws TooManyRegistrationAttemptsException (429 REGISTRATION__TOO_MANY_ATTEMPTS), which implements IRetryAfterException; the host's exception middleware sends its seconds as Retry-After. DisabledRegistrationIpLimitService is registered when RegistrationIpLimit:Enabled is false. With registration on and the limit off, the startup writes one warning. The sign-in limit uses the same IClientIpSlidingWindowService for its two unchanged scripts.
Breaking changes
The OpenAPI transformers no longer change the whole document.
ApiDocumentInfoTransformeris removed from the module with no shim:AddUsersApiModuleDocumentno longer sets the document title, version and description, so a host sets them itself (the Authentication Service host has its ownApiDocumentInfoTransformer). The session scheme is declared bySessionSecuritySchemeDocumentTransformer(SessionSchemeNamemoved there, same value), and the session requirement is added only to endpoints whose authorization usesAuthenticationSchemes.SessionKeyHeaderorAuthenticationSchemes.Session, not to every protected endpoint.No assignable feature list (Task 41).
IAssignableFeatureStorage,AssignableFeatureStorage,FeaturesByCodesNotFoundExceptionand theConstants.SystemFeaturesclasses of other services (ApplicationFeatures,DeviceFeatures,SerialPortConnectionFeatures,StationFeatures,TcpClientConnectionFeatures,TcpListenerConnectionFeatures) are removed with no shim, andAddUsersApiModuleno longer registers the storage.UserFeaturesmoved toApiFeatures.Authentications.Users.Constants(same values). Create-user stores the assigned features as sent (each must be non-empty); the services that own a permission define it. The removed check never rejected a feature, so no answer changes.The services of the module are given with
With...methods ofAddUsersApiModuleOptions(see "Services"). They are registered underServiceKeys.Defaultand resolved under that key only: anIJsonTool,IPhotoUploadServiceorIUserSessionResolverregistered by the host without the key is no longer used. A host must callWithJsonTool,WithPhotoUploadServiceandWithUserSessionResolver, or the startup tasks refuse to start.IPhotoServiceis also keyed now (defaultPhotoService, replaced withWithPhotoService).The photo upload service is the host's. The module's
IPhotoUploadService, itsImgBbUploadService, theModels/ImgBbstypes (ImgBbOption,ImgBbUploadResult,ImgBbImage,ApiResult<T>) andAddUsersApiModuleOptions.ImgBbare removed with no shim. The module usesIPhotoUploadServiceofBusinessFeatures.Images.Abstractions(new reference): a host must give one (the Authentication Service host gives theBusinessFeatures.Images.ImgBbsone), or the startup tasks refuse to start. An empty URL from the upload service fails the upload (InvalidOperationException) and no photo is stored.IJsonToolis the one ofBusinessFeatures.Cores. The module's ownApiFeatures.Authentications.Users.Services.Abstractions.IJsonTooland itsJsonToolare removed with no shim, andAddUsersApiModuleno longer registers a JSON tool. A host must give aBusinessFeatures.Cores.Services.Interfaces.IJsonTool(for examplenew JsonTool(options)with the Application settings), or the startup tasks refuse to start.The
GetUserBySessionKeyconsumer is back in the module.AddUsersApiModuleConsumersadds four consumers again. The consumer keeps its class name (so the queueGetUserBySessionKeyRequestMessageis unchanged) and its namespace is nowApiFeatures.Authentications.Users.Consumers. The module still does not reference the sessions package: a host must give anIUserSessionResolver(new), or the startup tasks refuse to start. A host must no longer add the consumer itself.No middleware and no error answers in the module (Task 34).
UseUsersApiModuleExceptionHandling,UseUsersApiModuleEndpointExceptionHandling, the three middleware, the exception response service and its interface, the authorization-exception policy evaluator and its item key,JsonSerializerKeys.DefaultCamelCaseandExceptionResponseMessages.InternalServerErrorare removed with no shim;AddUsersApiModuleno longer replacesIPolicyEvaluator. A host must answer the module's exceptions itself.ApiFeatures.Commonsis now 9.3.0.Sessions are no longer part of the module (Task 33). The module and its database libraries no longer reference the sessions package. The session endpoints and the endpoint class that mapped them, the session registration and cache decoration, the two session authentication schemes and their handler, the create-session check and the session limit, the session principal, the
GetUserBySessionKeyconsumer, the metadata redaction filter, the session constants and options (includingAddUsersApiModuleOptions.SessionStorageandAddUsersApiModuleOptions.AuthenticationSession) are removed from the module with no shim; they live in the Authentication Service host. A host must register the sessions package, the two session schemes and its own session endpoints, and declare those endpoints inVerifyUsersApiModuleEndpointsOptions(HostAnonymousEndpoints,HostProtectedEndpoints,HostJsonBodyEndpoints, new). New:IUserSignInServiceandIUserPrincipalService(user-level operations for the host session code) and the startup refusal when a scheme of the signed-in-user policy is missing. The module inventory is 11 endpoints (EndpointAccessRules.ApiEndpointCount) andAddUsersApiModuleConsumersadds three consumers.SessionMetadataKeysstays: it names the create-session metadata key of the reCAPTCHA token, a sign-in contract.Inline permission checks (Task 32). The endpoint feature attribute, its authorization requirement and handler, and the request-profile service and its interface are removed with no replacement and no shim. The signed-in-user policy now requires a signed-in, existing, active, not expired user only. The five endpoints that used the attribute check their permission inline and answer 403
FORBIDDEN(before: 403 with no body). The startup rule list of permission-protected endpoints is replaced byEndpointAccessRules.ModuleEndpoints, an inventory of the module endpoints (14 then, 11 since Task 33) without permissions.The system endpoint is no longer in the module (Task 31). The system endpoint mapping, the system version service and its interface, the system version model and their registration are removed with no replacement and no shim, and the startup tasks no longer load or log a version. A host that wants
GET api/system/versionmapsApiFeatures.Systems.Apisitself (the Authentication Service host does, inExtensions/ApplicationSystemFeatureExtensions.cs) and declares the endpoint inVerifyUsersApiModuleEndpointsOptions.HostAnonymousEndpoints; without the declaration the endpoint check refuses it.VerifyUsersApiModuleEndpointstakes an optionalVerifyUsersApiModuleEndpointsOptions(source compatible). Without options the check expects the module's endpoints only (11 since Task 33).These changes predate the first published version (10.0.0).
Embedded time zones (Task 47).
AddUsersApiModuleOptions.TimeZoneStoragePathis removed with no shim;TimeZoneService.ReloadAsyncis removed (the start-up tasks load the list); theTimeZoneServiceconstructor is internal (the service is registered by the module). The module no longer registersIFileSystemand no longer referencesTestableIO.System.IO.Abstractions: a host that resolvedIFileSystemonly through the module must register it itself (the Authentication Service host does).Resources/iana-tz.jsonis no longer copied to the output of projects that reference the module.Registration (Task 46).
MapAuthenticationApiEndpointstakesisRegistrationAllowed;RegisterUserPayloadDtorejects unknown members,EmailandCaptchaCodeare optional, and its validation uses the create-user rules (the old error codesUSERNAME_IS_REQUIRED,CAPTCHA_IS_REQUIRED, ... are gone).CreateUserCommand.Email,LanguageCodeandIanaTimeZoneIdare nullable.LegacyMediatorErrors.RegistrationNotImplementedMessageis removed.
Operations for the host session code
| Interface | Purpose |
|---|---|
IUserSignInService.SignInAsync(username, password, recaptchaToken, clientAddress) |
The sign-in check of create-session, in this order: the per-IP limit, reCAPTCHA, the username lock, the password (failure counts and lock release) and the account state. A counted failure is also added to the client address. Returns the user; every error passes through unchanged. Called by the create-session check of the host. |
IUserPrincipalService.CreateClaimsAsync(username) |
The claims of a signed-in user (the user claims, one role claim per role, one feature claim per assigned feature), or null when the user no longer exists. The host adds the session key claim. |
JSON
The module uses no JSON library. It reads and writes JSON only through IJsonSerializer (Services/Abstractions), which the host implements with the library of its choice and registers as a keyed service under every key of JsonSerializerKeys:
| Key | Settings |
|---|---|
JsonSerializerKeys.Application |
The same settings as the HTTP JSON options of the host (one definition): camel-case names and dictionary keys; case-insensitive reading; strictly typed input; comments skipped; trailing commas allowed; nulls written; cycles ignored; maximum depth 32; not indented; relaxed escaping; the C# required keyword ignored; doubles written with a fraction (105.0); enumerations as numbers; the pager and updatable-property shapes. |
- The host also configures its HTTP JSON options with the Application settings: the create-session body (bound by the framework), the answers of the sessions package and the OpenAPI schemas use them.
[SerializedName("x")]marks a property whose JSON name is an external contract (for exampleerror-codes); the serializer must use it as the exact name. It is also the form field name of the form binding.- A read failure (bad JSON, or a value that does not match the type) is thrown as
JsonContentException. Write failures are not wrapped. - The user cache uses the
IJsonToolofBusinessFeatures.Coresgiven withWithJsonTool, which must write the Application settings. A missing or unreadable cached user is a cache miss. - A host that did not register the serializers or give the JSON tool is refused at
RunUsersApiModuleStartupTasksAsync. - The Authentication Service host implements it with System.Text.Json in
AuthenticationService.Apis(AddApplicationJson()), and registers theBusinessFeatures.CoresJsonToolover the same options there.
Services
The With... methods of AddUsersApiModuleOptions give the module its services. Each has two forms: WithXxx<T>() (an implementation type, built by the container) and WithXxx(Func<IServiceProvider, T>) (a factory). They are registered under ServiceKeys.Default, after the defaults, so the last call of a method wins, and no service of the host is replaced.
| Method | Service | Lifetime | Default |
|---|---|---|---|
WithPhotoService |
IPhotoService (the image checks before the upload) |
Scoped | PhotoService |
WithPhotoUploadService |
IPhotoUploadService of BusinessFeatures.Images.Abstractions |
Scoped | none: required |
WithJsonTool |
IJsonTool of BusinessFeatures.Cores (the user cache) |
Singleton | none: required |
WithUserSessionResolver |
IUserSessionResolver (the GetUserBySessionKey consumer) |
Scoped | none: required |
A required service that was not given is refused at RunUsersApiModuleStartupTasksAsync.
Sign-in lockout
The sign-in lockout (AuthenticationService.AuthenticateWithLockoutAsync) keeps its state in the cache Redis of the host (IRedisClient), not in the database: USER__LOGIN__FAILURES_<username> (count, 24 hours after the last counted failure) and USER__LOGIN__UNLOCK_TIME_<username> (expires with the lock). Only a wrong password or unknown username counts; 5th to 10th failure locks 3 minutes, 11th and later 30 minutes. See docs/SessionAuthentication.md.
The per-IP limit (ISignInIpLimitService, called by IUserSignInService, which the host session code calls) runs first in create-session, before reCAPTCHA: RedisSignInIpLimitService keeps a sliding log per client address bucket (IPv4 address, IPv6 /64, or unknown) in the cache Redis, key USER__SIGN_IN__IP_FAILURES_<bucket>, and refuses with TooManyFailedLoginException carrying the retry time. A counted failure (InvalidUsernameOrPasswordException from the lockout-aware sign-in) is added after the username count. DisabledSignInIpLimitService is registered when SignInIpLimit:Enabled is false. The client address is HttpContext.Connection.RemoteIpAddress, after the host applied the forwarded headers of its trusted proxies.
Password hashing
IPasswordHashService (singleton) hashes with PBKDF2-HMAC-SHA256 (600,000 iterations, 16-byte salt, 32-byte output, UTF-8; constants in PasswordHashSettings) and verifies three stored formats: plain $pbkdf2-sha256$i=<n>$<salt>$<hash>, wrapped $pbkdf2-sha256-md5$i=<n>$<salt>$<hash> (a legacy MD5 value wrapped by the operator), and legacy MD5 (32 hexadecimal characters, checked as before over the ASCII bytes). Every Verify costs exactly one PBKDF2, whatever the stored value (null, empty or unrecognized values run a dummy derivation). AuthenticationService finds the user by username, verifies, and after a fully successful lockout-aware sign-in replaces a legacy, wrapped or weaker value through the compare-and-set IUserDatabaseService.ReplaceHashedPasswordAsync; a failed upgrade logs a warning without any hash and never changes the answer.
The operator-run wrap step is host.RunUsersApiModuleLegacyPasswordWrapAsync() (ILegacyPasswordWrapService): it replaces each legacy value with its wrapped form, is idempotent, returns the exit code (0 completed, 1 error) and must never be called at startup. The Authentication Service host runs it for the command word wrap-legacy-passwords. See the repository README, section 2.5.
Linux hosts (photo upload)
The module decodes uploaded photos with SkiaSharp 3.119.1 and references SkiaSharp.NativeAssets.Linux.NoDependencies (same version). That build needs no operating system package on glibc (Debian, Ubuntu) or on musl (Alpine), for x64, arm64 and arm, so a host on mcr.microsoft.com/dotnet/aspnet:*-alpine works with no apk add.
- Do not also reference
SkiaSharp.NativeAssets.Linuxin the host: both packages publish alibSkiaSharp.soto the same path. - The fontconfig build (
SkiaSharp.NativeAssets.Linux) fails to load on Alpine becauselibfontconfigis missing. A host that needs SkiaSharp text rendering with system fonts must switch both references to it and installfontconfig(apk add fontconfig, orapt-get install libfontconfig1). - When SkiaSharp is upgraded, upgrade
SkiaSharpand the native-assets package together. - Windows and macOS hosts need nothing extra.
Options
| Property | Required | Meaning |
|---|---|---|
Recaptcha |
No | reCAPTCHA settings. The check is on by default: registration fails when it is on and SecretKey is empty. |
IsRegistrationAllowed |
No | Maps the anonymous POST api/authentication/registration (Pending account with the USER role, reCAPTCHA token in captchaCode). Default false: the route does not exist (404), the startup check expects 19 endpoints instead of 20, and registered as IOptions<RegistrationOptions>. With it on and reCAPTCHA off the startup writes one warning. |
RegistrationIpLimit |
No | The per-client-IP limit of self-registration attempts: Enabled (default true), MaxAttempts (5, from 1 to 1000), WindowMinutes (60, from 1 to 1440). Registration of the module fails when a number is out of range, also when the limit or self-registration is off. |
SignInIpLimit |
No | The per-client-IP limit of failed create-session attempts: Enabled (default true), MaxFailures (10, from 1 to 1000), WindowMinutes (15, from 1 to 1440). Registration fails when a number is out of range. |
Resources
The time-zone list is embedded in the assembly as ApiFeatures.Authentications.Users.Resources.iana-tz.json. Nothing is copied to the output or publish folder, there is no setting or path, and a consumer cannot replace it. The list is loaded once, at start-up; the start fails with a message that names the resource (never a path) when it is missing, empty, not a JSON array of time zones, or holds no time zone. Create-user and update-user check the time zone with the same rule (ITimeZoneService.EnsureKnownAsync, exact comparison, 404 TIME_ZONE__NOT_FOUND); a field added later (for example in registration) must call it too.
| 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)
- ApiFeatures.Commons (>= 9.3.0)
- AuthenticationService.Commons (>= 10.2.0)
- BusinessFeatures.Cores (>= 9.0.1)
- BusinessFeatures.Images.Abstractions (>= 9.0.1)
- FluentValidation (>= 12.1.1)
- Microsoft.AspNetCore.OpenApi (>= 10.0.14)
- Serilog (>= 4.3.0)
- ServiceStack.Redis.Core (>= 6.0.0)
- SkiaSharp (>= 3.119.1)
- SkiaSharp.NativeAssets.Linux.NoDependencies (>= 3.119.1)
-
net9.0
- ApiFeatures.Authentications.Users.Cores (>= 10.0.0)
- ApiFeatures.Commons (>= 9.3.0)
- AuthenticationService.Commons (>= 10.2.0)
- BusinessFeatures.Cores (>= 9.0.1)
- BusinessFeatures.Images.Abstractions (>= 9.0.1)
- FluentValidation (>= 12.1.1)
- Serilog (>= 4.3.0)
- ServiceStack.Redis.Core (>= 6.0.0)
- SkiaSharp (>= 3.119.1)
- SkiaSharp.NativeAssets.Linux.NoDependencies (>= 3.119.1)
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. The Users module of the iot-vn Authentication Service: the user, registration, role assignment and time zone endpoints, the signed-in-user policy and the startup endpoint check, the MassTransit consumers, the user cache, reCAPTCHA, photo upload and the hosted services. Depends on ApiFeatures.Authentications.Users.Cores (>= 10.0.0) and AuthenticationService.Commons (>= 10.2.0). A host registers exactly one Users database package (ApiFeatures.Authentications.Users.Databases.Mongo or .Postgres) and must not also reference SkiaSharp.NativeAssets.Linux (this package brings SkiaSharp.NativeAssets.Linux.NoDependencies). Versioning: the major version is the highest .NET version targeted; minor versions can be breaking, so pin an exact version.