Audience: Engineers, DBAs, security reviewers. What this answers: how login, tenancy resolution, and permission enforcement actually work in code.

Source: IdentityService.cs (3,642 lines), MembershipService.cs (2,641), AccountService.cs (1,121), AdminRolesService.cs (687), CustomContextAccessorService.cs, JwtService.cs, IdentityModel.cs / AuthenticationModels.cs, MembershipDbContext / TenantDbContext, and web-app/src (auth store, RequireRoutePermit, usePermissions, permissions.ts). Line/count claims verified 2026-07-20.


1. Authentication flow

POST Identity/Authenticate  { username, password }
        │
        ▼
IdentityService.Authenticate(AuthenticationRequest)
   1. look up ApplicationUser in MembershipDb
   2. verify password
   3. gate checks → may return SignInStatus:
        Failed | LockedOut | NotAllowed
        | TwoFactorRequired | TwoFactorSetupRequired | PasswordResetRequired
   4. on Success → JwtService.GenerateTokens(...)
        │
        ▼
   AuthenticationResponse { access_token (JWT), refresh_token, status, context }

Entry points (IdentityService):

Method Purpose
Authenticate Standard username/password login.
ControlAuthenticate Internal control-panel staff (separate identity path).
SsoAuthenticate SSO (SsoAuthenticationRequest).
OAuthAuthenticate OAuth (Google/Microsoft — OAuthAuthenticationRequest).
RefreshAccessToken Exchange a refresh token for a new access token.
TwoFactorAuthenticate / TwoFactorCodeVerify Second-factor step.
GenerateEmailConfirmationToken / GeneratePasswordResetToken Out-of-band tokens.

Sign-in status (SignInStatusParams) is the switch the frontend reads to decide the next screen: Success, Failed, TwoFactorRequired, TwoFactorSetupRequired, PasswordResetRequired, LockedOut, NotAllowed.

2. The JWT — claims & signing

JwtService.GenerateTokens(username, encryptionKey, …, expiration):

Claim Notes
username, displayname, userid Identity.
organisationid, companyid Encrypted — decrypted per request.
organisationname Plain.
ewaid, companyewaid EWA linkage.
secretkey Per-token secret.
domain Tenant domain.
isadmin Fast admin flag.
context Sign-in context — see §4.
roles The tier(s).
permissions The per-permission grants.

Security note: organisationid / companyid are encrypted claim values, not plain ints — a decoded JWT does not leak raw tenant ids, and a tampered id fails decryption. See RFD-001.

3. Tenancy — the two-database model

PaidHR runs three DbContexts:

Context Scope Holds
MembershipDbContext Platform-wide master Identity (AspNetPermission, AspNetRolePermission, Users*, UserStatus/Suspension/Exit/Type, UserPasswordHistory), Organisation*, Company, reference data (Bank, Country, Currency), EWA config, Fusion HRIS.
TenantDbContext Per-tenant HR/operational data — Person • satellites, scoped by CompanyId. Resolved by TenantDbFactory.
WarehouseDbContext Analytics Reporting/warehouse.

Resolution per request — CustomContextAccessorService:

GetTokenFromHttpContext()            // pull Bearer token
   │
GetCredentials(token)
   ├─ context   = JwtService.GetClaimValue(token, CONTEXT)
   ├─ userid    = GetClaimValue(token, USER_ID)
   ├─ orgid     = (context==Owned||Acquired) ? decrypt(GetClaimValue(ORGANISATION_ID)) : null
   ├─ companyid = (context==Owned||Acquired) ? decrypt(GetClaimValue(COMPANY_ID))      : null
   │              // encryptionKey per env; long.TryParse / int.TryParse → 0 on miss
   ▼
PopulateCurrentContext(ContextAccessorModel)   // status, token, context, userName,
                                               // displayName, organisationName,
                                               // userId, organisationId, companyId, correlationId