Appearance
First Login Flow
This page documents the login flow when a user logs in for the first time or when password change is required.
Overview
When a user's account is created with a password set by someone else (an administrator), the IsFirstLogin and MustChangePassword flags are true. The login response includes these flags so the client can redirect the user to the password change screen before tenant selection.
Password is a user-level concern. The endpoint accepts the declared global, tenant and platform sessions. After changing the password it returns platform access for a platform role holder with an empty tenant overview, or a fresh global selection token in the other cases.
Triggers for Mandatory Password Change
| Condition | Description |
|---|---|
IsFirstLogin = true | User has never logged in |
MustChangePassword = true | The current password was set by someone else (temporary password) |
Expiry metadata alone does not open completion; IsFirstLogin or MustChangePassword must be set.
Both flags are cleared when the user sets a password they chose: by completing the first login (POST /api/v1/auth/complete-first-login) or by consuming a password reset link (POST /api/v1/auth/reset-password). The reset link does not count as a login (LastLoginAt is unchanged).
Sequence Diagram
100% 💡 Use Ctrl + Scroll para zoom | Arraste para navegar
Step-by-Step Explanation
Phase 1: Initial Login
1.1 Credential Validation
The user provides valid credentials. The system verifies:
- Email exists and user is active
- Password is correct
- AppId is valid (if configured)
1.2 Password Change Detection
After successful credential validation, the login response includes flags:
json
{
"isFirstLogin": true,
"mustChangePassword": true
}The client detects these flags and redirects to the password change form before tenant selection.
1.3 Global Token
For multi-tenant users without a default tenant, the login returns a global token:
json
{
"token": "eyJhbGciOiJSUzI1NiIs...",
"isGlobal": true,
"requiresTenantSelection": true,
"tokenType": "Global",
"availableTenants": [
{ "id": "...", "name": "Tenant A", "isDefault": false },
{ "id": "...", "name": "Tenant B", "isDefault": false }
]
}Token Properties
- TTL: 2 minutes (short-lived for security)
- Scope:
tenant-selector-only— cannot access tenant resources - Single-use: Enforced by the authorization handler
Phase 2: Complete First Login
2.1 Submit New Password
The client calls POST /api/v1/auth/complete-first-login with the accepted session token:
json
{
"currentPassword": "TemporaryPassword123!",
"newPassword": "NewSecurePassword456!",
"confirmPassword": "NewSecurePassword456!"
}Passwords are sent in plain text over TLS
Client-side RSA password encryption was removed in v5 — there is no GET /api/v1/auth/public-key endpoint and no isCurrentPasswordEncrypted/isNewPasswordEncrypted fields. Send both password fields directly over HTTPS. See password transport breaking change.
2.2 Password Validation Pipeline
The handler delegates to IPasswordChangeService (shared with change-password — DRY):
- Verify current (temporary) password matches
- Validate strength — minimum length, complexity, etc.
- Check history — prevents reusing the last N passwords
- Hash the new password and prepare user/history changes
2.3 Token Invalidation
The operation preserves the existing account-generation increments and synchronous invalidations:
csharp
user.CompleteFirstLogin(); // IsFirstLogin=false, MustChangePassword=false
user.InvalidateAllTokens("first_login_password_change");SetPasswordHash also increments the generation when PasswordSetAt already exists. The usual completion therefore advances it twice; historical credentials with that metadata absent can advance it once. The handler copies the actual final generation after saving the full event loop. It does not predict the increment or read a newer generation for issuance.
2.3.1 Commit Before Issuance
The handler uses the required Auth-specific ExecuteInOwnedTransactionAsync<TResult> capability. Existing/enlisted/ambient transactions, pending writes and pending aggregate events are refused before the operation mutates anything. Clean tracked entities are allowed. This prevents a host from receiving a new session from an outer transaction that can still roll back. Normal HTTP requests do not install such an outer transaction.
Validation/password refusals abort the owned attempt. The handler rechecks cancellation after the password service, which still converts some infrastructure errors into a generic failure. Exceptions escaping that service or the transaction protocol propagate without issuance. Only after commit and the existing flush/disposal protocol return does the handler materialize a session from copied identity, generation, flags and expiry data. It keeps no tracked User or password/hash in that output. The audit flush retains D11's existing behavior, including absorbed store failures; this is not a durable-audit guarantee.
If commit succeeded but cleanup or issuance fails, the password can already be changed. No session or automatic replay is returned; recover through normal login with the new password. Custom Auth unit-of-work implementations must implement the new capability without a nesting/Save fallback. See the ownership contract.
2.4 New Global Token
A fresh global token is generated with the operation's final TokenVersion. This allows the user to proceed to tenant selection without re-authenticating. This remains the output even for one/default tenant, and for an empty selection without a platform grant; it does not run smart login's automatic tenant selection.
A user with an empty tenant overview and a platform grant gets the platform session login issues them instead (ADR 0011, D8): tokenType: "Platform", no tenant_id, session_kind=platform, with a refresh token — there is no tenant to select. The endpoint accepts the restricted platform session the login returned.
MFA is not repeated. ICommittedFirstLoginCompletionReader binds the copied subject and exact final generation to grants in an independent primary RR/read-only view, without credentials or legacy cache. Fresh eligibility/cleared flags and cleanup are required; overview eligibility and nullable metadata retain legacy policy. Changed/ineligible proof returns 401 SESSION_INVALIDATED; unavailable preparation returns 503 AUTH_SESSION_PREPARATION_UNAVAILABLE, without signing, refresh or replay. Recover with the new password. Post-snapshot revocation and refresh/global or downstream legacy consistency remain separate work.
The global token response:
json
{
"token": "eyJhbGciOiJSUzI1NiIs...",
"isFirstLogin": false,
"mustChangePassword": false,
"isGlobal": true,
"requiresTenantSelection": true,
"availableTenants": [...]
}Why a new token?
- The original global token was consumed (single-use enforcement)
- The account generation advanced; versioned access/MFA use committed-generation validation
- The user has already proven their identity (valid token + correct old password + new password set)
- Forcing re-login would be redundant and poor UX
Phase 3: Tenant Selection
The user selects a tenant from availableTenants. This follows the standard Switch Tenant flow, producing a full tenant token (default 10-minute TTL, configurable 1–15 minutes via JwtSettings:ExpirationMinutes), a refresh token, roles, and permissions.
Error Scenarios
| Error | HTTP Status | Cause |
|---|---|---|
| Invalid current password | 400 | Temporary password doesn't match |
| Password reuse | 400 | New password matches a recent one |
| Weak password | 400 | Doesn't meet strength requirements |
| Passwords don't match | 400 | newPassword ≠ confirmPassword |
| Token expired | 401 | Global token expired (2 min TTL) |
| Token already used | 403 | Global token was already consumed |
| Not first login | 400 | User doesn't need to change password |
| Exclusive transaction boundary required | 400 | A host wrapped completion in an outer transaction or supplied pending Auth work |
| Session invalidated | 401 | Committed subject became ineligible or final generation changed |
| Session preparation unavailable | 503 | Independent preparation or cleanup failed |
Security Considerations
Global Token Limitations
The global token used during first login:
- Has a 2-minute TTL (short-lived)
- Is single-use (replay attack prevention)
- Contains no roles or permissions
- Cannot access tenant-scoped resources
- Is validated by
AllowGlobalAndTenantTokenHandler
The global token spent on complete-first-login is consumed: the client must continue with the new token returned by that operation. Replaying that consumed token returns 403. Other endpoints follow their declared consumption metadata; the attribute can explicitly disable consumption, so this is not a claim that every decorated endpoint consumes a global token.
Token Type Enforcement
Which token types an endpoint accepts is declared once, by its authorization attribute, via IAllowedTokenTypesMetadata:
| Attribute | Accepted token_type |
|---|---|
[AllowGlobalAndTenantToken] | global, access |
[RequireMfaPendingToken] | mfa_pending |
anything else (e.g. [Authorize]) | access only (fail-secure default) |
GrydAuthTokenProcessor reads that metadata from the routed endpoint. It does not keep an allowlist of its own — a second, path-keyed allowlist is what previously rejected complete-first-login with a 401 WrongTokenType even though the endpoint's attribute accepted global tokens.
Two consequences worth knowing:
UseGrydAuth()must run afterUseRouting(). Without a routed endpoint the processor falls back to the access-only allowlist and logs a warning.TokenTypeAllowlistContractTestsfails the build if an endpoint's policy and its declared token types ever disagree again.
Password History
Password history prevents:
- Reusing recent passwords (configurable count via
PasswordPolicyOptions.PasswordHistoryCount) - Cycling through passwords to return to a favorite
- Predictable password rotation
Token Invalidation
After password change:
TokenVersionis incremented in the database- Versioned access/MFA compare their positive generation for equality against the committed primary
- Existing blacklists and cache evictions remain; their external effects can survive SQL rollback
- Refresh/global revocation and their reissuance rules remain separate work; this page does not promise that every token family is protected by the access/MFA generation gate
Code Example
Client-Side Flow (TypeScript)
This pseudocode illustrates the global-selection branch. Clients must also handle the platform result without sending it to tenant selection. Refresh credentials remain in HttpOnly cookies; they are not read from the authentication JSON body.
typescript
async function handleLogin(email: string, password: string) {
const response = await authService.login({ email, password });
if (response.data.isFirstLogin || response.data.mustChangePassword) {
// Store global token and redirect to password change
authStore.setGlobalToken(response.data.token);
authStore.setAvailableTenants(response.data.availableTenants);
router.push('/change-password');
return;
}
if (response.data.requiresTenantSelection) {
// Multi-tenant user, go to tenant selection
authStore.setGlobalToken(response.data.token);
authStore.setAvailableTenants(response.data.availableTenants);
router.push('/select-tenant');
return;
}
// Single tenant or auto-switched — ready to go
authStore.setAccessToken(response.data.token); // refresh stays in its HttpOnly cookie
router.push('/dashboard');
}
async function handleFirstLoginPasswordChange(
currentPassword: string,
newPassword: string
) {
const globalToken = authStore.getGlobalToken();
const response = await authService.completeFirstLogin({
currentPassword,
newPassword,
confirmPassword: newPassword
}, globalToken);
// Response contains NEW global token + available tenants
authStore.setGlobalToken(response.data.token);
authStore.setAvailableTenants(response.data.availableTenants);
// Now go to tenant selection
router.push('/select-tenant');
}
async function handleTenantSelection(tenantId: string) {
const globalToken = authStore.getGlobalToken();
const response = await authService.switchTenant({ tenantId }, globalToken);
// Full tenant token received
authStore.setAccessToken(response.data.token); // refresh stays in its HttpOnly cookie
router.push('/dashboard');
}Related Flows
- Login Flow - Standard login with default tenant
- Switch Tenant - Tenant selection after login