diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor index ce103e79..f94420bb 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor @@ -50,11 +50,8 @@ - - @(_session.IsRevoked ? "Revoked" : IsExpired ? "Expired" : "Session active") + + @SessionStatusText @@ -124,10 +121,9 @@ - @@ -168,7 +164,8 @@ - Based on the last recorded activity. Successful refreshes may reset this deadline. + Based on the last recorded server activity. + A successful session touch may reset this deadline. @@ -176,28 +173,79 @@ - + + + + + + + + + + NEXT REFRESH ELIGIBILITY + + + + + + + + @RefreshEligibilityCountdown + + + + @RefreshEligibilityDescription + + + + + + + + + + - + - NEXT AUTOMATIC REFRESH + NEXT BACKGROUND REFRESH - @AutomaticRefreshCountdown + @BackgroundRefreshCountdown - Client coordinator · Every 10 minutes - - - Automatic attempts: @Diagnostics.AutomaticRefreshCount + @if (BackgroundRefreshEnabled) + { + + The next attempt scheduled by the background coordinator. + + } + else + { + + No periodic refresh requests are sent while the application is inactive. + + } + + @@ -311,6 +359,204 @@ + + + Refresh Strategies + + UltimateAuth coordinates refresh operations according to the configured client strategies. + Concurrent requests can share a single refresh execution. + + + + + + + + + Proactive + + + @(ProactiveRefreshEnabled ? "Enabled" : "Disabled") + + + + + @Diagnostics.ProactiveRefreshCount + + + + Refresh before an eligible + authenticated request. + + + + + + + + + + + + + + + + + + Reactive + + + + @(ReactiveRefreshEnabled + ? "Enabled" + : "Disabled") + + + + + + @Diagnostics.ReactiveRefreshCount + + + + Recover from a supported authentication + challenge when a renewable access token + is available. + + + + + + + + + + + + + + + + + + Background + + + + @(BackgroundRefreshEnabled + ? "Enabled" + : "Disabled") + + + + + + @Diagnostics.BackgroundRefreshCount + + + + Refresh independently of + authenticated application requests. + + + + + + + + + + + + + + + + + + Manual attempts + + + + @Diagnostics.ManualRefreshCount + + + + + + + + Recovery attempts + + + + @Diagnostics.RecoveryRefreshCount + + + + + + + + Total refresh attempts + + + + @Diagnostics.RefreshAttemptCount + + + + + + + + Counters represent refresh transport attempts + within the current client scope. + Requests sharing a refresh execution are not + counted separately. + + + @if (!BackgroundRefreshEnabled && ProactiveRefreshEnabled) + { + + Identity Lab uses request-driven refresh. + Sessions are not periodically renewed + while the application is inactive. + + } + + + + + @@ -369,6 +615,13 @@ Refresh session + + Send authenticated request + @@ -398,7 +651,8 @@ Validation checks session validity. - Refresh follows the active authentication mode and does not necessarily rotate a token. + Manual refresh explicitly requests renewal. + An authenticated request may trigger proactive refresh when the current authentication is eligible. diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor.cs b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor.cs index 5eb9be62..e0d1df05 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor.cs +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Components/Pages/Dashboard/SessionDiagnostics.razor.cs @@ -30,13 +30,41 @@ private sealed record RefreshFeedback(string Title, string Description, Color Co private DateTimeOffset _now = DateTimeOffset.UtcNow; private readonly CancellationTokenSource _timerCts = new(); + private int SessionChangingRefreshResults => + Diagnostics.RefreshTouchedCount + + Diagnostics.RefreshRotatedCount + + Diagnostics.RefreshSuccessCount; + + private string SessionStatusText => + _session?.IsRevoked == true + ? "Revoked" + : IsExpired + ? "Expired" + : IsIdleExpired + ? "Idle expired" + : "Session active"; + + private Color SessionStatusColor => + _session?.IsRevoked == true + ? Color.Error + : IsExpired || IsIdleExpired + ? Color.Warning + : Color.Success; + protected override async Task OnInitializedAsync() { _disposed = false; - Diagnostics.Changed += OnDiagnosticsChanged; _policy = PolicyService.Get(); + _observedSessionChangingRefreshResults = SessionChangingRefreshResults; + + Diagnostics.Changed += OnDiagnosticsChanged; + await LoadAsync(); - _ = RunClockAsync(_timerCts.Token); + + if (!_disposed) + { + _ = RunClockAsync(_timerCts.Token); + } } private bool IsExpired => _session is { } session && session.ExpiresAt <= _now; @@ -107,13 +135,11 @@ private void UpdateLifetimeTracking(SessionInfo session) private static double GetPercent(DateTimeOffset start, DateTimeOffset end, DateTimeOffset totalEnd) { - // This helper will be replaced with a - // shared timeline scale in the final implementation. + // This helper will be replaced with a shared timeline scale in the final implementation. return 0; } - private double NowPosition => - TimelinePosition(_now); + private double NowPosition => TimelinePosition(_now); private double ExtensionStartPosition => _initialExpiresAt is { } initial @@ -128,16 +154,9 @@ _initialExpiresAt is not null && _session is not null private readonly SemaphoreSlim _syncGate = new(1, 1); - private int _observedRefreshResults; + private int _observedSessionChangingRefreshResults; private bool _disposed; - private int CompletedRefreshResults => - Diagnostics.RefreshTouchedCount + - Diagnostics.RefreshRotatedCount + - Diagnostics.RefreshNoOpCount + - Diagnostics.RefreshReauthRequiredCount + - Diagnostics.RefreshSuccessCount; - private async Task LoadAsync() { if (_disposed) @@ -342,12 +361,84 @@ IdleExpiresAt is { } expiry ? FormatCountdown(expiry, "Idle limit reached") : "Disabled"; + private bool ProactiveRefreshEnabled => + _policy?.ProactiveRefreshEnabled == true; + + private bool ReactiveRefreshEnabled => + _policy?.ReactiveRefreshEnabled == true; + + private bool BackgroundRefreshEnabled => + _policy?.BackgroundRefreshEnabled == true; + + private bool ScheduledRefreshEnabled => + ProactiveRefreshEnabled || BackgroundRefreshEnabled; + private string AutoRefreshIntervalText => - _policy?.AutoRefreshEnabled == true && - _policy.AutoRefreshInterval is { } interval - ? $"{interval.TotalMinutes:0} minutes" + ScheduledRefreshEnabled && + _policy?.AutoRefreshInterval is { } interval + ? $"{interval.TotalMinutes:0.##} minutes" : "Disabled"; + private bool IsIdleExpired => + IdleExpiresAt is { } expiry && expiry <= _now; + + private string RefreshEligibilityCountdown + { + get + { + if (!ScheduledRefreshEnabled) + return "Disabled"; + + if (_session?.IsRevoked == true || + IsExpired || IsIdleExpired) + return "Session expired"; + + if (Diagnostics.NextRefreshEligibleAt is not { } next) + return "Not available"; + + return FormatCountdown(next, "Eligible now"); + } + } + + private string BackgroundRefreshCountdown + { + get + { + if (!BackgroundRefreshEnabled) + return "Disabled"; + + if (Diagnostics.IsTerminated) + return "Terminated"; + + if (!Diagnostics.IsRunning) + return "Not running"; + + if (Diagnostics.NextAutomaticRefreshAt is not { } next) + return "Not scheduled"; + + return FormatCountdown(next, "Due now"); + } + } + + private string RefreshEligibilityDescription => + (ProactiveRefreshEnabled, BackgroundRefreshEnabled) switch + { + (true, true) => + "Refresh may be triggered by an authenticated request " + + "or the background coordinator.", + + (true, false) => + "Refresh is attempted before the next eligible " + + "authenticated request. No background request is scheduled.", + + (false, true) => + "Refresh is triggered by the background coordinator " + + "when eligible.", + + _ => + "Scheduled refresh strategies are disabled." + }; + private string FormatCountdown(DateTimeOffset target, string completedText) { var remaining = target - _now; @@ -385,20 +476,6 @@ await InvokeAsync(() => } } - private string AutomaticRefreshCountdown - { - get - { - if (!Diagnostics.IsRunning) - return "Not running"; - - if (Diagnostics.NextAutomaticRefreshAt is not { } next) - return "Scheduling..."; - - return FormatCountdown(next, "Due now"); - } - } - private static RefreshFeedback GetRefreshFeedback(RefreshOutcome outcome) { return outcome switch @@ -468,18 +545,21 @@ private void OnDiagnosticsChanged() if (_disposed) return; - var completed = CompletedRefreshResults; + var completed = SessionChangingRefreshResults; - if (completed != _observedRefreshResults) - { - _observedRefreshResults = completed; + var sessionChanged = completed != _observedSessionChangingRefreshResults; - if (!_manualRefreshInProgress) - await SyncSessionAsync(); + _observedSessionChangingRefreshResults = completed; + + if (sessionChanged && !_manualRefreshInProgress) + { + await SyncSessionAsync(); } if (!_disposed) + { StateHasChanged(); + } }); } @@ -545,6 +625,91 @@ private string SlidingExtensionText } } + private async Task SendAuthenticatedRequestAsync() + { + if (_busy || _disposed) + return; + + _busy = true; + _lastRefresh = null; + + var proactiveBefore = Diagnostics.ProactiveRefreshCount; + var reactiveBefore = Diagnostics.ReactiveRefreshCount; + + try + { + var result = await UAuthClient.Sessions.GetMyChainsAsync( + new PageRequest + { + PageNumber = 1, + PageSize = 20 + }); + + var proactiveAttempted = + Diagnostics.ProactiveRefreshCount > proactiveBefore; + + var reactiveAttempted = + Diagnostics.ReactiveRefreshCount > reactiveBefore; + + if (!result.IsSuccess) + { + _lastRefresh = new RefreshFeedback( + "Authenticated request unsuccessful", + "The protected endpoint did not return a successful result.", + Color.Warning, + Icons.Material.Filled.WarningAmber); + } + else if (proactiveAttempted) + { + _lastRefresh = new RefreshFeedback( + "Authenticated request completed", + "A proactive refresh attempt was recorded while " + + "the authenticated request was being processed.", + Color.Success, + Icons.Material.Filled.Autorenew); + } + else if (reactiveAttempted) + { + _lastRefresh = new RefreshFeedback( + "Authenticated request completed", + "A reactive refresh attempt was recorded while " + + "the authenticated request was being processed.", + Color.Success, + Icons.Material.Filled.Autorenew); + } + else + { + _lastRefresh = new RefreshFeedback( + "Authenticated request completed", + "No new refresh transport attempt was recorded.", + Color.Info, + Icons.Material.Filled.CheckCircle); + } + + Snackbar.Add( + _lastRefresh.Title, + result.IsSuccess + ? Severity.Success + : Severity.Warning); + } + catch (Exception) + { + _lastRefresh = new RefreshFeedback( + "Authenticated request failed", + "The protected request could not be completed.", + Color.Error, + Icons.Material.Filled.ErrorOutline); + + Snackbar.Add( + _lastRefresh.Title, + Severity.Error); + } + finally + { + _busy = false; + } + } + public ValueTask DisposeAsync() { _timerCts.Cancel(); diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Program.cs b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Program.cs index e09f1ed5..9a3dfaed 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Program.cs +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Program.cs @@ -70,7 +70,6 @@ builder.Services.AddUltimateAuthClientBlazor(o => { - o.AutoRefresh.Enabled = true; o.AutoRefresh.Interval = TimeSpan.FromMinutes(10); o.Reauth.Behavior = ReauthBehavior.RaiseEvent; o.Resource.Credentials = UAuthResourceCredentialsMode.SameOrigin; diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabManagementClient.cs b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabManagementClient.cs index b8acecfa..ea2550e8 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabManagementClient.cs +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabManagementClient.cs @@ -1,4 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Abstractions; using System.Text.Json; namespace CodeBeam.UltimateAuth.IdentityLab.Services; diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs index 81ad22e7..734c852c 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs @@ -10,8 +10,11 @@ public sealed record LabSessionDiagnosticsPolicy( TimeSpan? IdleTimeout, TimeSpan? MaxLifetime, bool SlidingExpiration, - bool AutoRefreshEnabled, + bool BackgroundRefreshEnabled, + bool ProactiveRefreshEnabled, + bool ReactiveRefreshEnabled, TimeSpan? AutoRefreshInterval, + TimeSpan RefreshBeforeExpiration, int? MaxDevices, IReadOnlyDictionary DeviceTypeLimits, DeviceLimitBehavior DeviceLimitBehavior); @@ -29,10 +32,15 @@ public LabSessionDiagnosticsPolicy Get() session.IdleTimeout, session.MaxLifetime, session.SlidingExpiration, - autoRefresh.Enabled, + autoRefresh.Background, + autoRefresh.Proactive, + autoRefresh.Reactive, autoRefresh.Interval, + autoRefresh.RefreshBeforeExpiration, serverOptions.Value.DeviceLimits.MaxDevices, - new Dictionary(serverOptions.Value.DeviceLimits.TypeLimits, StringComparer.OrdinalIgnoreCase), + new Dictionary( + serverOptions.Value.DeviceLimits.TypeLimits, + StringComparer.OrdinalIgnoreCase), serverOptions.Value.DeviceLimits.Behavior); } } diff --git a/docs/content/auth-flows/refresh-flow.md b/docs/content/auth-flows/refresh-flow.md index f09f737b..ac86c9b4 100644 --- a/docs/content/auth-flows/refresh-flow.md +++ b/docs/content/auth-flows/refresh-flow.md @@ -10,6 +10,10 @@ Refresh is how an existing authentication context continues without asking the u A successful refresh preserves the authenticated identity and its continuity. It does **not** prove the user's credentials again, create a new login, or necessarily extend every lifetime associated with the authentication. +> This guide describes server-side refresh execution. +> +> For client-side scheduling, proactive renewal, reactive recovery, background refresh, and concurrent request coordination, see [Automatic Refresh](/docs/client-sdk/automatic-refresh). + ## The model: continuity, not a second login UltimateAuth distinguishes three related operations: @@ -153,7 +157,11 @@ The HTTP endpoint returns **`204 No Content`** on successful refresh and **`401 `RefreshFlowResult` also recognizes `Success` as a successful outcome, although the mode-specific branches described above return `NoOp`, `Touched`, `Rotated` or `ReauthRequired`. -Clients should serialize refresh attempts where practical. Parallel refresh requests using the same token do not produce multiple valid replacements, even when they fall within the concurrency window. +The UltimateAuth Client SDK coordinates refresh attempts through a shared single-flight mechanism within the current client scope. + +Custom clients should implement appropriate refresh coordination to avoid unnecessary concurrent rotation attempts. + +Server-side rotation and replay protection remain necessary across independent client scopes, applications, and devices. ## Security boundaries @@ -173,8 +181,9 @@ These controls complement one another. A refresh token should be treated as a se The useful distinction is not simply *stateful versus stateless*. It is **what must remain valid for authentication to continue**: - `PureOpaque` continues an existing server-side session, with conditional activity updates. -- `Hybrid` requires both session validity and successful refresh-token rotation. -- Other rotation branches exist, but are not part of the completed v0.1.0 supported-mode set. +- `Hybrid` requires session validity and successful refresh-token rotation. +- `SemiHybrid` describes JWT renewal with server-managed lifecycle state. +- `PureJwt` rotates refresh credentials through a session-independent refresh chain. Refresh does not authenticate a user again. It extends the usefulness of an already established authentication context only within the boundaries of the selected mode and configured security policies. diff --git a/docs/content/client-sdk/authentication.md b/docs/content/client-sdk/authentication.md index 51c496fc..976802ef 100644 --- a/docs/content/client-sdk/authentication.md +++ b/docs/content/client-sdk/authentication.md @@ -724,36 +724,32 @@ The parameter distinguishes automatic refresh activity for client diagnostics. It does not select a different authentication mode or override the server's refresh policy. -## 10. Automatic Refresh Configuration -UltimateAuth exposes client-side automatic refresh options through `AutoRefresh`. +## 10. Automatic Refresh -```csharp -options.AutoRefresh.Enabled = true; -options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); -``` +Applications do not need to manually refresh authentication before every protected request. -`Enabled` controls background refresh coordination. +UltimateAuth enables proactive and reactive refresh by default. -`Interval` specifies the interval used for background refresh attempts. - -The effective defaults and registration behavior depend on the client integration. The options documentation identifies Blazor Server as the environment where background refresh is enabled by default. +```csharp +builder.Services.AddUltimateAuthClientBlazor(options => +{ + options.AutoRefresh.Proactive = true; + options.AutoRefresh.Reactive = true; + options.AutoRefresh.Background = false; +}); +``` -### Automatic Refresh Is Not a Security Guarantee +Proactive refresh renews authentication before eligible authenticated requests. -Automatic refresh is a client-side convenience mechanism. +Reactive refresh provides recovery from supported authentication challenges. -It does not guarantee that a session will remain valid indefinitely. +Background refresh can be enabled when independent authentication renewal is required. -Authentication may still end because of: +Manual refresh remains available through `UAuthClient.Flows.RefreshAsync()`. -- Expiration. -- Revocation. -- Account security changes. -- Invalid refresh credentials. -- Server-side continuation restrictions. +For configuration, credential-aware scheduling, concurrency, session policy alignment, and diagnostics, see the dedicated [Automatic Refresh](/docs/client-sdk/automatic-refresh) guide. -The client must remain prepared to handle `ReauthRequired`. ## 11. Validate Current Authentication diff --git a/docs/content/client-sdk/authorization.md b/docs/content/client-sdk/authorization.md index 886f9532..aeb83b30 100644 --- a/docs/content/client-sdk/authorization.md +++ b/docs/content/client-sdk/authorization.md @@ -1,6 +1,6 @@ --- title: Authorization -order: 7 +order: 8 group: client --- diff --git a/docs/content/client-sdk/automatic-refresh.md b/docs/content/client-sdk/automatic-refresh.md new file mode 100644 index 00000000..75ceed90 --- /dev/null +++ b/docs/content/client-sdk/automatic-refresh.md @@ -0,0 +1,870 @@ +--- +title: Automatic Refresh +order: 3 +group: client +--- + +# Automatic Refresh + +Authentication should not become an application-level scheduling problem. + +UltimateAuth provides a coordinated refresh mechanism that can renew authentication before a protected request, recover from supported authentication challenges, or maintain authentication through background execution. + +Applications do not need to implement their own token expiration timers, refresh locks, or authentication retry pipelines when using the supported UltimateAuth client operations. + +The same client architecture supports different authentication modes and credential lifecycles without requiring applications to implement a separate refresh strategy for each mode. + +## 1. Getting Started + +Automatic refresh is available through the UltimateAuth Client SDK and its supported platform integrations. + +For Blazor applications, register the client as usual: + +```csharp +builder.Services.AddUltimateAuthClientBlazor(); +``` + +Proactive and reactive refresh are enabled by default. Background refresh is opt-in. + +The following configuration makes the defaults explicit: + +```csharp +builder.Services.AddUltimateAuthClientBlazor(options => +{ + options.AutoRefresh.Proactive = true; + options.AutoRefresh.Reactive = true; + options.AutoRefresh.Background = false; + + options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); + options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1); +}); +``` + +Once authentication is established, supported client operations participate in refresh coordination automatically. + +For example: + +```csharp +var result = await UAuthClient.Resource + .GetAsync>("/api/products"); + +if (result.IsSuccess) +{ + products = result.Value; +} +``` + +The application does not need to check token expiration or explicitly refresh authentication before every request. + +For client registration and configuration, see [Client Options](/docs/configuration/client-options). + +## 2. Three Automatic Refresh Strategies + +UltimateAuth provides three independently configurable automatic refresh strategies. + +| Strategy | Trigger | Enabled by default | +|---|---|---| +| Proactive | Before an eligible authenticated request | Yes | +| Reactive | After a supported authentication challenge | Yes | +| Background | When the background coordinator reaches its refresh schedule | No | + +These strategies complement each other. They share the same refresh coordination and credential management infrastructure. + +Enabling multiple strategies does not create independent refresh pipelines. + +### Proactive Refresh + +Proactive refresh checks whether authentication is eligible for renewal before sending a supported authenticated request. + +When refresh is due, the client attempts to renew authentication first. + +```text +Application request + | + v +Is refresh due? + | + +-- No --> Send request + | + +-- Yes --> Refresh authentication + | + v + Send request +``` + +This avoids unnecessary authentication challenges when the client already knows that renewal is appropriate. + +For example, when a JWT is approaching expiration: + +```text +POST /auth/refresh -> 204 +GET /api/products -> 200 +``` + +Without proactive refresh, the application might first encounter an expired-token challenge. + +Proactive refresh is particularly useful for applications that should renew authentication while being used, without continuously refreshing during inactivity. + +> Tip: Keep proactive refresh enabled even when background refresh is disabled. Request-driven renewal provides authentication continuity without requiring a continuously running refresh timer. + +### Reactive Refresh + +Reactive refresh attempts to recover from a supported authentication challenge. + +When a protected request is rejected before application execution, the client can attempt refresh and replay the original request using a renewed access token. + +```text +GET /api/products -> 401 +POST /auth/refresh -> 204 +GET /api/products -> 200 +``` + +Reactive refresh is a recovery mechanism rather than the primary refresh schedule. + +It is useful when: + +- A token expires between preparation and request execution. +- An application resumes after being suspended. +- The server rejects an access token that the client expected to remain valid. +- A concurrent request has already renewed the access token. + +The client does not blindly retry every unsuccessful request. + +Recovery requires a supported authentication challenge and an appropriate access-token lifecycle. + +A request is replayed at most once through this recovery pipeline. + +The following responses do not independently trigger authentication recovery: + +- `403 Forbidden` +- `429 Too Many Requests` +- Arbitrary application-generated `401` responses +- Network failures +- Server errors + +Reactive recovery currently requires a usable access-token context for safe replay. Cookie-only session authentication does not receive the same automatic replay behavior. + +> Tip: Proactive refresh reduces the number of expected authentication challenges. Reactive refresh remains useful as a fallback for expiration races and unexpected authentication rejection. + +### Background Refresh + +Background refresh allows the client coordinator to initiate renewal without waiting for an application request. + +Enable it explicitly: + +```csharp +builder.Services.AddUltimateAuthClientBlazor(options => +{ + options.AutoRefresh.Background = true; +}); +``` + +Background refresh is useful for applications that need to maintain authentication during periods without protected requests. + +Examples include: + +- Operational dashboards. +- Monitoring applications. +- Long-running interactive workspaces. +- Applications where users spend significant time editing local state before submitting it. + +Background refresh requires an active client coordinator and an execution environment capable of running it. + +It cannot guarantee renewal while a browser tab is suspended, a device is offline, an application has been closed, or its execution environment has stopped. + +Server-side expiration, revocation, and refresh policies continue to apply. + +> Tip: Enable background refresh because your application needs independent authentication renewal, not simply because it supports long-lived sessions. + +## 3. How Refresh Timing Works + +UltimateAuth uses a shared refresh schedule. + +The schedule adapts to the credential available to the client. + +There are two primary scheduling mechanisms: + +- Interval-based scheduling. +- JWT expiration-based scheduling. + +Applications do not need to run both mechanisms as independent timers. + +### Interval-Based Scheduling + +When the client has an established authentication context without a managed JWT access token, refresh eligibility is determined by `Interval`. + +```csharp +options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); +``` + +The interval is measured from the establishment of the authenticated schedule or the last successful refresh. + +For example: + +```text +12:00 Authentication established +12:02 Protected request +12:05 Refresh becomes eligible +12:08 Protected request triggers proactive refresh +12:08 Refresh succeeds +12:13 Refresh becomes eligible again +``` + +With background refresh disabled, no refresh request is sent at 12:05 simply because the interval has elapsed. + +The next eligible authenticated request initiates renewal. + +This scheduling mechanism is particularly useful for opaque session authentication. + +### JWT Expiration-Based Scheduling + +When a managed JWT access token is available, the client uses its expiration time. + +```csharp +options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1); +``` + +For example: + +```text +12:00 Access token issued +12:09 Refresh becomes eligible +12:10 Access token expires +``` + +The client becomes eligible for refresh one minute before expiration. + +If the configured threshold is greater than or equal to the remaining token lifetime when its schedule is initialized, UltimateAuth reduces the effective threshold to half of that remaining lifetime. + +This prevents short-lived access tokens from immediately entering a continuous refresh cycle. + +For example, a newly received token with a remaining lifetime of 30 seconds and a configured refresh threshold of one minute becomes eligible after approximately 15 seconds. + +The schedule belongs to the credential itself. Repeated validation or repeated schedule checks do not continuously postpone its refresh time. + +### Interval vs. RefreshBeforeExpiration + +| Option | Used when | +|---|---| +| `Interval` | Authentication uses an interval-based schedule without a managed JWT | +| `RefreshBeforeExpiration` | A managed JWT access token provides an expiration time | + +These options describe alternative scheduling mechanisms rather than competing refresh timers. + +Both proactive and background refresh use the applicable shared schedule. + +Reactive refresh responds to authentication challenges independently of scheduled eligibility. + +## 4. Authentication Modes + +Refresh behavior depends on both the authentication mode and the credentials delivered to the client. + +| Mode | Typical scheduling | Refresh behavior | +|---|---|---| +| PureOpaque | Interval | Continue an existing server-side session | +| Hybrid | Interval or JWT expiration, depending on the managed credential | Validate session continuity and rotate refresh credentials | +| PureJwt | JWT expiration | Rotate refresh credentials and obtain a replacement access token | +| SemiHybrid | JWT expiration when supported | JWT renewal with server-managed lifecycle state | + +PureOpaque does not require a separate access-token and refresh-token pair. + +Its refresh operation may update recorded session activity and extend session expiration according to server policy. + +Hybrid combines server-authoritative session state with additional credential lifecycles. The actual client schedule depends on the credential delivered and managed by the client. + +PureJwt uses session-independent JWT authentication with a stateful refresh-token lifecycle. + +SemiHybrid describes the JWT-based session-backed model. Its complete runtime support is still evolving; applications should not assume that every SemiHybrid scenario is currently available. + +### Cookie-Only Authentication + +Automatic refresh does not require the application to possess a readable access token. + +For example, PureOpaque can use a server-managed session cookie with interval-based proactive or background refresh. + +The client can initiate the refresh operation without reading the session credential from the cookie. + +Reactive access-token replay has additional requirements and should not be assumed to work identically for cookie-only authentication. + +For a complete comparison, see [Authentication Modes](/docs/fundamentals/auth-modes). + +## 5. Choose the Right Strategy + +### Recommended Default + +For most interactive applications: + +```csharp +options.AutoRefresh.Proactive = true; +options.AutoRefresh.Reactive = true; +options.AutoRefresh.Background = false; +``` + +This configuration renews authentication when supported application activity requires it and provides reactive recovery where available. + +It avoids continuously sending refresh requests simply because an application remains open. + +### Continuous Authentication Maintenance + +For applications that need independent renewal: + +```csharp +options.AutoRefresh.Proactive = true; +options.AutoRefresh.Reactive = true; +options.AutoRefresh.Background = true; +``` + +The strategies share refresh coordination, so overlapping refresh triggers do not independently rotate the same credential within the client scope. + +### Reactive-Only Recovery + +For specialized applications that prefer recovery after authentication challenges: + +```csharp +options.AutoRefresh.Proactive = false; +options.AutoRefresh.Reactive = true; +options.AutoRefresh.Background = false; +``` + +This configuration is primarily useful with managed, renewable access tokens. + +It may introduce an additional failed request before successful recovery. + +It is not a replacement for session maintenance in cookie-only opaque authentication. + +### Manual Refresh Only + +Applications can disable all three automatic strategies: + +```csharp +options.AutoRefresh.Proactive = false; +options.AutoRefresh.Reactive = false; +options.AutoRefresh.Background = false; +``` + +Explicit refresh remains available: + +```csharp +var result = await UAuthClient.Flows.RefreshAsync(); +``` + +Disabling automatic refresh strategies does not necessarily disable initial authentication recovery performed by the client state integration. + +## 6. Why Proactive Refresh Is Efficient + +Consider an application that remains open for eight hours but receives authenticated application requests during only two hours. + +With a five-minute refresh interval: + +- Background refresh could attempt renewal throughout the eight-hour period. +- Proactive refresh attempts renewal only when an eligible authenticated request is made. + +Under simplified conditions with sufficiently frequent requests: + +| Strategy | Illustrative refresh attempts | +|---|---:| +| Background refresh | 96 | +| Proactive refresh | Approximately 24 | + +This represents approximately 75% fewer refresh attempts in this example. + +Actual results depend on the distribution of requests, successful refresh times, authentication validity, rate limiting, and execution environment. + +Proactive refresh is request-driven, not a direct measurement of human activity. + +An application that continuously polls protected endpoints may continue renewing authentication even when the user is not interacting with its interface. + +> Tip: If preserving meaningful idle expiration is important, review automatic application polling as well as background refresh configuration. + +## 7. Coordinated Refresh and Concurrent Requests + +A common authentication problem occurs when multiple requests discover that an access token needs renewal at the same time. + +Without coordination: + +```text +Request A -> Refresh +Request B -> Refresh +Request C -> Refresh +Request D -> Refresh +``` + +Concurrent rotation can introduce unnecessary traffic, conflicting credential updates, or refresh-token reuse. + +UltimateAuth coordinates refresh through a shared single-flight mechanism. + +```text +Request A --+ +Request B --+ +Request C --+--> Shared refresh execution +Request D --+ | + v + Updated authentication +``` + +Concurrent callers can wait for the same refresh execution rather than independently sending refresh requests. + +The coordination infrastructure is shared by proactive, reactive, background, manual, and initial recovery operations. + +The client also tracks authentication lifecycle and credential changes to prevent stale refresh results from overwriting a newer client authentication context. + +For example: + +- A user logs out while a refresh is in progress. +- A different user signs in before an earlier refresh completes. +- A delayed authentication challenge arrives after another request has already renewed the access token. + +The client can reject stale results or reuse an already renewed credential where appropriate. + +This coordination applies within the current client scope. + +It does not provide distributed locking across browser tabs, independent applications, or multiple devices. + +Server-side rotation and replay protection remain essential. + +See [Refresh Rotation & Replay Protection](/docs/security/refresh-rotation). + +## 8. Safe Authentication Recovery and Request Replay + +Automatic request replay must distinguish authentication rejection from application execution. + +UltimateAuth uses an authentication recovery response marker for supported authentication challenges. + +The client does not interpret every `401 Unauthorized` response as permission to replay an operation. + +This distinction matters for requests that modify application state: + +```csharp +var result = await UAuthClient.Resource.PostAsync("/api/orders", request); +``` + +Supported resource operations can participate in authentication recovery regardless of their HTTP method. + +However, authentication replay is limited to the supported recovery contract and requires an appropriate renewed credential. + +It is not a general-purpose HTTP retry policy. + +Applications should not emit the authentication recovery marker from business logic after performing a mutation. + +A custom endpoint that performs side effects before returning an authentication challenge can violate the assumptions required for safe replay. + +Business-level idempotency remains important for operations that must tolerate retries from networks, proxies, or other infrastructure. + +### Which Requests Participate? + +Automatic request preparation and recovery are available through: + +- Supported authenticated UltimateAuth Client SDK operations. +- The UltimateAuth Resource Client. +- Other integrations explicitly connected to the refresh recovery infrastructure. + +Not every authentication flow or SDK endpoint necessarily participates in automatic request replay. + +An arbitrary `HttpClient` request, direct JavaScript fetch, or server-side service invocation does not automatically enter this pipeline. + +For protected application API integration, see [Resource API Requests](/docs/client-sdk/resource-api-requests). + +## 9. Session Touch, Sliding Expiration, and Idle Timeout + +Client refresh scheduling and server session policies are separate responsibilities. + +Consider the following server configuration: + +```csharp +builder.Services.AddUltimateAuthServer(options => +{ + options.Session.Lifetime = TimeSpan.FromDays(7); + options.Session.SlidingExpiration = true; + options.Session.TouchInterval = TimeSpan.FromMinutes(5); + options.Session.IdleTimeout = TimeSpan.FromDays(4); +}); +``` + +And the following client configuration: + +```csharp +builder.Services.AddUltimateAuthClientBlazor(options => +{ + options.AutoRefresh.Interval = TimeSpan.FromMinutes(10); + options.AutoRefresh.Proactive = true; + options.AutoRefresh.Background = false; +}); +``` + +Each option serves a different purpose. + +| Option | Responsibility | +|---|---| +| `AutoRefresh.Interval` | Client refresh eligibility | +| `Session.TouchInterval` | Minimum interval for ordinary server-side session touches | +| `Session.SlidingExpiration` | Whether a successful touch can extend session expiration | +| `Session.IdleTimeout` | Maximum permitted time without recorded session activity | +| `Session.Lifetime` | Session expiration policy | +| `Session.MaxLifetime` | Maximum chain lifetime when configured | + +### Refresh Does Not Always Touch a Session + +A refresh request can succeed without changing server-side session state. + +For example: + +```csharp +options.Session.TouchInterval = TimeSpan.FromMinutes(5); +``` + +If the client attempts refresh every 30 seconds, ordinary refresh requests may return `NoOp` until the server touch interval has elapsed. + +This is valid behavior, but it can produce unnecessary refresh traffic. + +For interval-based opaque authentication, a useful starting point is: + +```text +TouchInterval <= AutoRefresh.Interval +``` + +This is a configuration recommendation rather than a universal requirement. + +JWT expiration and refresh-token rotation may require renewal independently of the server touch interval. + +Explicit server-side force-touch behavior may also bypass the ordinary touch interval. + +### Sliding Expiration + +A successful session touch may extend expiration when sliding expiration is enabled. + +Both proactive and background refresh can participate in this behavior. + +The server remains responsible for applying the session lifetime and any configured maximum lifetime. + +Refresh cannot revive a session that has already expired or bypass an applicable absolute lifetime limit. + +### Idle Timeout + +Idle expiration is based on recorded server-side session activity. + +It is not necessarily reset by every protected request. + +With proactive refresh, ordinary requests that occur before refresh eligibility may not update the server's recorded activity. + +Consequently, the recorded idle duration can differ from the time since the user's last interaction. + +Configure the refresh interval and touch interval with sufficient margin below the idle timeout. + +For example: + +```text +TouchInterval: 1 minute +AutoRefresh.Interval: 5 minutes +IdleTimeout: 30 minutes +``` + +This configuration provides more scheduling margin than using a refresh interval close to the idle timeout. + +It still does not guarantee that a session will remain valid without a timely eligible request. + +Background refresh can keep recorded activity current even when the user is inactive. This may be desirable for continuous workspaces, but it may also prevent idle expiration from reflecting human inactivity. + +> Tip: If the purpose of IdleTimeout is to expire inactive user sessions, prefer request-driven renewal and avoid unnecessary protected polling. + +See [Session Model & Lifecycle](/docs/sessions-devices/session-lifecycle) and [Server Options](/docs/configuration/server-options). + +## 10. Rate Limiting and Refresh Backoff + +Refresh is an authentication operation and remains subject to server-side rate limiting. + +When the server returns `429 Too Many Requests`, the client observes the applicable retry delay instead of immediately starting another refresh attempt. + +A rate-limited refresh does not independently mean that the user has been logged out. + +The client can preserve the existing authentication context while renewal is temporarily unavailable. + +Whether an application request can continue depends on the available credential and its validity. + +UltimateAuth also applies automatic refresh backoff when a successful refresh does not rotate an existing JWT. + +This prevents repeated proactive or background attempts from creating a tight refresh loop. + +A successful refresh response does not make an expired access token valid again. + +Applications should handle unsuccessful request results normally and must not assume that every refresh attempt produces usable replacement credentials. + +See [Rate Limiting](/docs/security/rate-limiting). + +## 11. Manual Refresh and Authentication Recovery + +Automatic refresh does not remove explicit authentication operations. + +Applications can still request refresh directly: + +```csharp +var result = await UAuthClient.Flows.RefreshAsync(); + +if (result.IsSuccess) +{ + // Authentication continuation succeeded. +} +else if (result.Outcome == RefreshOutcome.ReauthRequired) +{ + // Authentication must be established again. +} +``` + +Manual refresh participates in the shared coordination infrastructure. + +It does not bypass server expiration, rotation, revocation, or rate-limiting policies. + +### Authentication Recovery After Reload + +A client may start without a managed access token, for example after a full browser reload. + +When a compatible refresh credential remains available, the client can attempt authentication recovery. + +```csharp +var result = await UAuthClient.Flows.RecoverAsync(); +``` + +Initial recovery differs from reactive request replay. + +Its purpose is to restore authentication when the client does not currently have usable access material. + +Recovery remains subject to server policy and browser credential availability. + +See [Authentication](/docs/client-sdk/authentication). + +## 12. Refresh Outcomes + +Refresh is not synonymous with token rotation. + +The result depends on the authentication mode and the server's refresh policy. + +| Outcome | Meaning | +|---|---| +| `NoOp` | Authentication continuation succeeded without requiring a session update | +| `Touched` | Recorded session activity was updated | +| `Rotated` | Refresh credentials were rotated | +| `Success` | Generic successful refresh | +| `ReauthRequired` | Authentication cannot safely continue through the attempted refresh | + +Applications should inspect `RefreshResult.IsSuccess` rather than requiring a particular successful outcome. + +Detailed refresh outcomes may depend on the server diagnostics configuration: + +```csharp +builder.Services.AddUltimateAuthServer(options => +{ + options.Diagnostics.EnableRefreshDetails = true; +}); +``` + +A generic success result does not necessarily mean that a session was touched or that a token was rotated. + +For server-side execution details, see [Refresh Flow](/docs/auth-flows/refresh-flow). + +## 13. Client Diagnostics + +UltimateAuth exposes refresh diagnostics through `UAuthClientDiagnostics`. + +A Blazor component can inject the diagnostics service: + +```razor +@using CodeBeam.UltimateAuth.Client.Diagnostics +@inject UAuthClientDiagnostics Diagnostics +``` + +The available counters distinguish refresh operations by their initiating trigger. + +| Property | Meaning | +|---|---| +| `ProactiveRefreshCount` | Proactive transport attempts | +| `ReactiveRefreshCount` | Reactive transport attempts | +| `BackgroundRefreshCount` | Background transport attempts | +| `ManualRefreshCount` | Explicit manual transport attempts | +| `RecoveryRefreshCount` | Authentication recovery transport attempts | +| `AutomaticRefreshCount` | Combined proactive, reactive, and background attempts | +| `RefreshAttemptCount` | Total transport attempts | + +Counters represent transport attempts, not individual callers waiting for a shared refresh execution. + +Locally deferred operations do not independently increment transport attempt counters. + +Outcome counters are also available: + +- `RefreshTouchedCount` +- `RefreshRotatedCount` +- `RefreshNoOpCount` +- `RefreshSuccessCount` +- `RefreshReauthRequiredCount` + +### Refresh Eligibility vs. Background Scheduling + +Two diagnostic timestamps describe different aspects of refresh timing. + +```csharp +var eligibleAt = Diagnostics.NextRefreshEligibleAt; +var backgroundAt = Diagnostics.NextAutomaticRefreshAt; +``` + +`NextRefreshEligibleAt` describes the initialized refresh schedule for the current authentication context. + +`NextAutomaticRefreshAt` describes the next attempt scheduled by the background coordinator. + +With proactive refresh enabled and background refresh disabled, the eligibility timestamp can be available while the background timestamp remains null. + +Eligibility does not guarantee that a request will be sent at that time. + +Temporary backoff, rate limiting, authentication changes, and execution environment constraints can affect actual execution. + +Reading diagnostics does not initiate a refresh or initialize a new JWT refresh schedule. + +### Observing Changes in Blazor + +Components can subscribe to diagnostic changes: + +```razor +@implements IDisposable + +
+ Proactive attempts: @Diagnostics.ProactiveRefreshCount +
+ +
+ Background attempts: @Diagnostics.BackgroundRefreshCount +
+ +@code { + protected override void OnInitialized() + { + Diagnostics.Changed += OnDiagnosticsChanged; + } + + private void OnDiagnosticsChanged() + { + _ = InvokeAsync(StateHasChanged); + } + + public void Dispose() + { + Diagnostics.Changed -= OnDiagnosticsChanged; + } +} +``` + +Use diagnostic notifications to update application displays. + +Avoid initiating authentication operations synchronously from diagnostic event handlers. + +For a countdown display, a local UI timer can update the displayed remaining time without sending authentication requests. + +### Client Scope + +Diagnostics describe the current client scope. + +They are not application-wide telemetry, server-wide counters, or persistent per-user audit records. + +Counters may accumulate across authentication changes within the same client scope. + +Applications that need centralized monitoring should use an appropriate telemetry or logging integration. + +## 14. Troubleshooting + +### Refresh Never Runs When the Application Is Idle + +**Cause:** Background refresh is disabled. + +**Solution:** This is expected with proactive refresh. Send a supported authenticated request after refresh eligibility is reached, or enable background refresh if independent renewal is required. + +### Refresh Succeeds but Session Expiration Does Not Change + +**Cause:** The server may return `NoOp`, sliding expiration may be disabled, or a maximum lifetime may prevent further extension. + +**Solution:** Review server session policies and detailed refresh outcomes. + +### Too Many Refresh Requests Return NoOp + +**Cause:** The client refresh interval may be shorter than the server touch interval. + +**Solution:** Align the intervals for opaque session authentication. + +### A Short-Lived JWT Refreshes Earlier Than Expected + +**Cause:** The configured refresh threshold may be greater than the remaining token lifetime. + +**Solution:** UltimateAuth clamps the effective threshold when initializing the schedule. Review the access-token lifetime and refresh threshold together. + +### A 401 Response Does Not Trigger Reactive Refresh + +**Cause:** The response may not represent a supported authentication challenge, the operation may not participate in recovery, or a renewable managed access token may be unavailable. + +**Solution:** Verify the request integration, credential delivery, authentication recovery marker, and reactive configuration. + +For cross-origin browser requests, ensure the required response headers are exposed through CORS. + +### Background Refresh Is Enabled but Not Running + +**Cause:** The client coordinator may not be started, authentication may not be established, or the application execution environment may be suspended. + +**Solution:** Review the client integration and coordinator diagnostics. + +### Authentication Expires Despite Automatic Refresh + +**Cause:** The session, refresh token, or authentication chain may have expired or been revoked. A required credential may also be unavailable. + +**Solution:** Handle reauthentication appropriately. Automatic refresh cannot override server security policy. + +## 15. Configuration Reference + +| Option | Default | Purpose | +|---|---|---| +| `Proactive` | `true` | Refresh before eligible authenticated requests | +| `Reactive` | `true` | Recover from supported authentication challenges | +| `Background` | `false` | Enable independent background refresh | +| `Interval` | 5 minutes | Interval-based refresh eligibility | +| `RefreshBeforeExpiration` | 1 minute | JWT expiration-based refresh threshold | + +The effective interval defaults to five minutes after client option configuration. + +The equivalent configuration can be expressed through appsettings.json: + +```json +{ + "UltimateAuth": { + "Client": { + "AutoRefresh": { + "Proactive": true, + "Reactive": true, + "Background": false, + "Interval": "00:05:00", + "RefreshBeforeExpiration": "00:01:00" + } + } + } +} +``` + +## Summary + +UltimateAuth separates authentication renewal from application business logic. + +Proactive refresh provides efficient request-driven renewal. + +Reactive refresh provides recovery from supported authentication challenges. + +Background refresh provides independent renewal when the application requires it. + +All strategies share refresh coordination and credential lifecycle management within the current client scope. + +The recommended starting point is proactive and reactive refresh with background refresh disabled. + +Enable additional behavior according to the application's continuity requirements rather than implementing independent authentication timers and retry mechanisms. + +## Related Documentation + +- [Authentication](/docs/client-sdk/authentication) — Login, logout, manual refresh, and authentication recovery. +- [Resource API Requests](/docs/client-sdk/resource-api-requests) — Protected application requests and supported recovery behavior. +- [Client Options](/docs/configuration/client-options) — Client configuration reference. +- [Server Options](/docs/configuration/server-options) — Server authentication and session policies. +- [Authentication Modes](/docs/fundamentals/auth-modes) — Credential and authentication lifecycle differences. +- [Refresh Flow](/docs/auth-flows/refresh-flow) — Server-side refresh execution. +- [Session Model & Lifecycle](/docs/sessions-devices/session-lifecycle) — Session expiration, touch, and sliding expiration. +- [Refresh Rotation & Replay Protection](/docs/security/refresh-rotation) — Refresh-token concurrency and replay protection. +- [Rate Limiting](/docs/security/rate-limiting) — Authentication rate limits and server enforcement. diff --git a/docs/content/client-sdk/credentials.md b/docs/content/client-sdk/credentials.md index 7b665805..791affc8 100644 --- a/docs/content/client-sdk/credentials.md +++ b/docs/content/client-sdk/credentials.md @@ -1,6 +1,6 @@ --- title: Credentials -order: 6 +order: 7 group: client --- diff --git a/docs/content/client-sdk/identifiers.md b/docs/content/client-sdk/identifiers.md index e0e82737..afad4550 100644 --- a/docs/content/client-sdk/identifiers.md +++ b/docs/content/client-sdk/identifiers.md @@ -1,6 +1,6 @@ --- title: Identifiers -order: 5 +order: 6 group: client --- diff --git a/docs/content/client-sdk/overview.md b/docs/content/client-sdk/overview.md index 11744a08..51fc3531 100644 --- a/docs/content/client-sdk/overview.md +++ b/docs/content/client-sdk/overview.md @@ -21,6 +21,7 @@ The Client SDK is more than a collection of HTTP methods. It brings together several responsibilities: - **Authentication workflows** — Start login, refresh, logout, and other supported authentication operations. +- **Automatic authentication renewal** — Coordinate proactive, reactive, and background refresh without application-specific token timers or authentication retry pipelines. - **Session management** — Interact with available session and device management capabilities. - **User management** — Retrieve and manage user information through the appropriate API contracts. - **Credential operations** — Manage credentials and initiate supported recovery workflows. @@ -242,6 +243,7 @@ The following guides cover the major client responsibilities with practical C# e | Guide | What you will learn | |---|---| | **Authentication** | Login, logout, refresh, PKCE, and authentication state handling | +| [Automatic Refresh](/docs/client-sdk/automatic-refresh) | Configure authentication renewal, refresh scheduling, recovery, and diagnostics | | **Session Management** | Retrieve, inspect, and manage sessions and device-associated chains | | **User Management** | Retrieve user information and perform supported user lifecycle operations | | **Identifiers** | Manage email addresses, usernames, phone numbers, and verification workflows | @@ -255,6 +257,8 @@ Each guide focuses on a specific developer task and includes the relevant SDK me If you are integrating UltimateAuth for the first time, start with **Authentication**. +Continue with [Automatic Refresh](/docs/client-sdk/automatic-refresh) to understand how UltimateAuth maintains authentication during normal application activity and recovers from supported authentication challenges. + Once login and authentication state handling work correctly, continue with **Resource API Requests** to connect authentication to your application's protected functionality. After that, use the domain-specific guides for the features your application needs. diff --git a/docs/content/client-sdk/resource-api-requests.md b/docs/content/client-sdk/resource-api-requests.md index 6d10eb0c..71f0c8c2 100644 --- a/docs/content/client-sdk/resource-api-requests.md +++ b/docs/content/client-sdk/resource-api-requests.md @@ -1,6 +1,6 @@ --- title: Resource API Requests -order: 8 +order: 9 group: client --- @@ -809,34 +809,28 @@ The goal is to remove unnecessary integration work whenever an HTTP resource req --- -## 11. Handling Unauthorized Responses +## 11. Authentication Renewal and Unauthorized Responses -An authenticated session may expire or become invalid while an application is running. +The Resource Client participates in UltimateAuth's coordinated authentication renewal infrastructure. -When a Resource API returns `401 Unauthorized`, the Resource Client exposes the unsuccessful HTTP response through its standard result contract. +With proactive refresh enabled, an eligible request can renew authentication before being sent to the Resource API. + +With reactive refresh enabled, a supported authentication challenge can trigger credential renewal and a single request replay. + +For example: ```csharp var result = await UAuthClient.Resource.GetAsync>("/api/products"); -if (!result.IsSuccess && result.Status == 401) +if (result.IsSuccess) { - // Authentication may need to be renewed. + products = result.Value; } ``` -### Automatic Refresh and Retry - -The current Resource Client does not automatically refresh authentication and retry a request after receiving a `401` response. - -This behavior is intentionally outside the initial Resource API implementation. - -Applications should not assume that an unsuccessful request has been retried. - -Authentication renewal and retry policies require careful handling, particularly for requests that modify application state. - -Future improvements may provide additional coordination between resource requests and authentication lifecycle management. +The application does not need to manually inspect token expiration or implement its own authentication retry loop. -Until then, applications should handle unauthorized responses according to their authentication flow and UI requirements. +See [Automatic Refresh](/docs/client-sdk/automatic-refresh) --- diff --git a/docs/content/client-sdk/session-management.md b/docs/content/client-sdk/session-management.md index eb63b166..8b2720db 100644 --- a/docs/content/client-sdk/session-management.md +++ b/docs/content/client-sdk/session-management.md @@ -1,6 +1,6 @@ --- title: Session Management -order: 3 +order: 4 group: client --- diff --git a/docs/content/client-sdk/user-management.md b/docs/content/client-sdk/user-management.md index d9670e21..3f0c9f37 100644 --- a/docs/content/client-sdk/user-management.md +++ b/docs/content/client-sdk/user-management.md @@ -1,6 +1,6 @@ --- title: User Management -order: 4 +order: 5 group: client --- diff --git a/docs/content/configuration/client-options.md b/docs/content/configuration/client-options.md index c82dbbf2..c0d7d646 100644 --- a/docs/content/configuration/client-options.md +++ b/docs/content/configuration/client-options.md @@ -98,7 +98,7 @@ The client controls the application-side integration. | `Endpoints` | `UAuthClientEndpointOptions` | Authentication endpoint paths | | `Login` | `UAuthClientLoginFlowOptions` | Login flow configuration | | `Pkce` | `UAuthClientPkceLoginFlowOptions` | PKCE flow configuration | -| `AutoRefresh` | `UAuthClientAutoRefreshOptions` | Background refresh coordination | +| `AutoRefresh` | `UAuthClientAutoRefreshOptions` | Proactive, reactive, and background refresh coordination | | `Reauth` | `UAuthClientReauthOptions` | Reauthentication behavior | | `MultiTenant` | `UAuthClientMultiTenantOptions` | Tenant propagation | | `StateEvents` | `UAuthStateEventOptions` | Authentication state event handling | @@ -596,91 +596,45 @@ Open redirects can be abused for phishing and other attacks. Prefer local application routes unless cross-origin navigation is an intentional and validated part of the authentication architecture. + ## 9. Automatic Refresh -`options.AutoRefresh` controls background refresh coordination. +`options.AutoRefresh` controls client-side authentication renewal. -The available properties are: +UltimateAuth provides three independently configurable automatic refresh strategies. -| Property | Description | -|---|---| -| `Enabled` | Enables or disables automatic background refresh | -| `Interval` | Interval between background refresh attempts | - -### Configure Automatic Refresh +| Property | Default | Purpose | +|---|---|---| +| `Proactive` | `true` | Refresh before eligible authenticated requests | +| `Reactive` | `true` | Recover from supported authentication challenges | +| `Background` | `false` | Refresh independently of application requests | +| `Interval` | 5 minutes | Interval-based refresh eligibility | +| `RefreshBeforeExpiration` | 1 minute | JWT expiration-based refresh threshold | ```csharp builder.Services.AddUltimateAuthClientBlazor(options => { - options.AutoRefresh.Enabled = true; - options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); -}); -``` + options.AutoRefresh.Proactive = true; + options.AutoRefresh.Reactive = true; + options.AutoRefresh.Background = false; -### Disable Automatic Refresh - -```csharp -builder.Services.AddUltimateAuthClientBlazor(options => -{ - options.AutoRefresh.Enabled = false; + options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); + options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1); }); ``` -### Default Interval +Proactive and reactive refresh are enabled by default. -If `Interval` is not supplied, the client registration applies: +Background refresh is opt-in and requires an active client coordinator. -```csharp -options.AutoRefresh.Interval ??= TimeSpan.FromMinutes(5); -``` +The client uses interval-based or JWT expiration-based scheduling according to the available managed credential. -The resulting default interval is five minutes. +All refresh strategies share coordination infrastructure within the current client scope. -### Platform Behavior +Automatic refresh does not override server-side expiration, revocation, device binding, or rate-limiting policies. -The effective `Enabled` setting should be considered together with the platform's post-configuration and session coordination behavior. +For strategy selection, scheduling behavior, session policy alignment, request replay, and diagnostics, see [Automatic Refresh](/docs/client-sdk/automatic-refresh). -The current Blazor session coordinator checks `AutoRefresh.Enabled` before starting its background loop. - -When enabled, it periodically invokes: - -```csharp -UAuthClient.Flows.RefreshAsync(true); -``` - -### Automatic Refresh Is Not a Security Policy - -Automatic refresh does not control: - -- Server session lifetime. -- Refresh token lifetime. -- Session revocation. -- Credential recovery policies. -- Refresh token replay protection. - -These remain server-side responsibilities. - -### Automatic Refresh Does Not Guarantee Session Continuity - -Background refresh may fail because: - -- The session has expired. -- The refresh credential has been revoked. -- The browser is suspended. -- Network connectivity is unavailable. -- The server requires reauthentication. - -Automatic refresh is a convenience and continuity mechanism, not a guarantee that authentication remains valid indefinitely. - -### Coordinator Lifecycle - -The Blazor adapter provides an `ISessionCoordinator` implementation. - -The coordinator must be started by the application's supported initialization lifecycle. - -Setting `AutoRefresh.Enabled = true` does not mean that a background task automatically runs without the coordinator being started. - -Applications should follow the client initialization guidance for their hosting model. ## 10. Reauthentication Options @@ -913,7 +867,7 @@ For example: "AutoRedirect": true }, "AutoRefresh": { - "Enabled": true, + "Background": true, "Interval": "00:05:00" }, "Reauth": { @@ -1065,7 +1019,8 @@ builder.Services.AddUltimateAuthClientBlazor(options => options.Pkce.AutoRedirect = true; // Background refresh - options.AutoRefresh.Enabled = false; + options.AutoRefresh.Background = false; + options.AutoRefresh.Proactive = true; // Reauthentication options.Reauth.Behavior = ReauthBehavior.Redirect; @@ -1099,7 +1054,8 @@ builder.Services.AddUltimateAuthClientBlazor(options => options.Login.ReturnUrl = "/dashboard"; // Background refresh - options.AutoRefresh.Enabled = true; + options.AutoRefresh.Background = false; + options.AutoRefresh.Proactive = true; options.AutoRefresh.Interval = TimeSpan.FromMinutes(5); // Reauthentication @@ -1139,7 +1095,7 @@ builder.Services.AddUltimateAuthClientBlazor(options => options.ApplicationProfile = UAuthApplicationProfile.BlazorServer; options.AutoDetectApplicationProfile = false; options.Endpoints.BasePath = "/auth"; - options.AutoRefresh.Enabled = true; + options.AutoRefresh.Proactive = true; }); ``` @@ -1154,7 +1110,7 @@ The two configuration objects have different responsibilities. | Allowed authentication modes | Server | | Application profile | Client | | PKCE navigation | Client | -| Automatic background refresh | Client | +| Automatic proactive refresh | Client | | Reauthentication navigation | Client | | Authentication state event handling | Client | | Tenant validation | Server | @@ -1224,7 +1180,11 @@ The current client registration validates options when they are resolved, rather | `Pkce.ReturnUrl` | `null` | PKCE return URL | | `Pkce.AutoRedirect` | `true` | Automatic PKCE navigation | | `Pkce.OnAuthorized` | `null` | PKCE authorization callback | -| `AutoRefresh.Interval` | 5 minutes after post-configuration | Background refresh interval | +| `AutoRefresh.Proactive` | `true` | Refresh before eligible authenticated requests | +| `AutoRefresh.Reactive` | `true` | Recover from supported authentication challenges | +| `AutoRefresh.Background` | `false` | Independent background refresh coordination | +| `AutoRefresh.Interval` | 5 minutes | Interval-based refresh eligibility | +| `AutoRefresh.RefreshBeforeExpiration` | 1 minute | JWT expiration-based refresh threshold | | `Reauth.Behavior` | `Redirect` | Reauthentication handling | | `Reauth.RedirectPath` | `null` | Reauthentication redirect | | `MultiTenant.Enabled` | `false` | Tenant propagation | @@ -1234,12 +1194,11 @@ The current client registration validates options when they are resolved, rather | `Resource.BaseAddress` | `null` | Resource API origin; defaults to application origin | | `Resource.Credentials` | `Auto` | Browser credential handling for resource requests | -`AutoRefresh.Enabled` should be evaluated with the applicable platform and post-configuration behavior rather than inferred solely from its property initializer. - ## Next Steps -- **Configuration Overview** — Understand the configuration architecture and source precedence. -- **Server Options** — Configure authentication security, sessions, tokens, and endpoints. -- **Advanced Configuration** — Explore effective options, mode resolution, and extension points. -- **Client Authentication** — Implement login, PKCE, refresh, and logout flows. -- **Client Session Management** — Manage authenticated sessions and revocation. +- [Configuration Overview](/docs/configuration/overview) — Understand the configuration architecture and source precedence. +- [Server Options](/docs/configuration/server-options) — Configure authentication security, sessions, tokens, and endpoints. +- [Advanced Configuration](/docs/configuration/advanced-configuration) — Explore effective options, mode resolution, and extension points. +- [Authentication](/docs/client-sdk/authentication) — Implement login, PKCE, refresh, and logout flows. +- [Automatic Refresh](/docs/client-sdk/automatic-refresh) — Configure efficient authentication renewal, automatic recovery, and refresh coordination. +- [Session Management](/docs/client-sdk/session-management) — Manage authenticated sessions and revocation. diff --git a/docs/content/sessions-devices/session-lifecycle.md b/docs/content/sessions-devices/session-lifecycle.md index 24a7b465..4b3780e0 100644 --- a/docs/content/sessions-devices/session-lifecycle.md +++ b/docs/content/sessions-devices/session-lifecycle.md @@ -255,7 +255,7 @@ Session continuity and activity management are handled through the applicable op ### Hybrid -Hybrid uses distinct opaque access and refresh credentials backed by server-authoritative session state. +Hybrid combines server-authoritative session state with additional access-token and refresh-token lifecycles. Refresh operations can renew authentication material while preserving the appropriate session or chain relationship. diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/auth-flows/refresh-flow.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/auth-flows/refresh-flow.json index 20763899..015556b6 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/auth-flows/refresh-flow.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/auth-flows/refresh-flow.json @@ -1,7 +1,7 @@ { "Slug": "auth-flows/refresh-flow", "Title": "Refresh", - "Html": "\n\u003Cp\u003ERefresh is how an existing authentication context continues without asking the user to authenticate again. In UltimateAuth, it is not synonymous with issuing a new access token: the operation depends on the active authentication mode and on whether the context is represented by a server-side session, refresh credentials, or both.\u003C/p\u003E\n\u003Cp\u003EA successful refresh preserves the authenticated identity and its continuity. It does \u003Cstrong\u003Enot\u003C/strong\u003E prove the user\u0027s credentials again, create a new login, or necessarily extend every lifetime associated with the authentication.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-model-continuity-not-a-second-login\u0022\u003EThe model: continuity, not a second login\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth distinguishes three related operations:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthentication\u003C/strong\u003E establishes a new authenticated context after the required proof is accepted.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ERefresh\u003C/strong\u003E attempts to continue an already established context, subject to its current validity and security policies.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReauthentication\u003C/strong\u003E establishes trust again when continuation is unavailable or no longer permitted.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis distinction matters for both security and client behavior. A refresh request can fail because a session expired, a refresh credential is invalid or consumed, the device context does not match, or the underlying chain is no longer usable. The client should treat an unsuccessful refresh as a need to authenticate again, not as an invitation to retry the same credential indefinitely.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022mode-dependent-strategies\u0022\u003EMode-dependent strategies\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EContinuation mechanism\u003C/th\u003E\n\u003Cth\u003ERequired state\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque\u003C/td\u003E\n\u003Ctd\u003ESession touch\u003C/td\u003E\n\u003Ctd\u003EValid server-side session\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid\u003C/td\u003E\n\u003Ctd\u003ESession-backed refresh-token rotation\u003C/td\u003E\n\u003Ctd\u003EValid session and refresh token\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESemiHybrid\u003C/td\u003E\n\u003Ctd\u003EPlanned\u003C/td\u003E\n\u003Ctd\u003ENot currently supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureJwt\u003C/td\u003E\n\u003Ctd\u003ERefresh-token rotation\u003C/td\u003E\n\u003Ctd\u003EValid refresh token and refresh chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt-refresh-without-a-session\u0022\u003EPureJwt: refresh without a session\u003C/h3\u003E\n\u003Cp\u003EPureJwt uses a persisted refresh-token chain without requiring an authentication session.\u003C/p\u003E\n\u003Cp\u003EThe refresh operation:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates the refresh token, tenant, and device binding.\u003C/li\u003E\n\u003Cli\u003EVerifies that the token is associated with a valid refresh chain and is not session-bound.\u003C/li\u003E\n\u003Cli\u003EResolves the authenticated user\u0027s current identity information and claims.\u003C/li\u003E\n\u003Cli\u003EGenerates replacement access and refresh credentials.\u003C/li\u003E\n\u003Cli\u003EAtomically consumes the previous refresh token and persists its replacement.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe new JWT access token can be validated independently by Resource APIs.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022concurrent-requests-and-replay-protection\u0022\u003EConcurrent requests and replay protection\u003C/h3\u003E\n\u003Cp\u003EA consumed refresh token cannot be used for another successful rotation.\u003C/p\u003E\n\u003Cp\u003EThe configured concurrent-request window distinguishes likely overlapping refresh requests from later reuse attempts.\u003C/p\u003E\n\u003Cp\u003EReuse outside that window can revoke the associated refresh chain.\u003C/p\u003E\n\u003Cp\u003EFor PureJwt, this revocation does not require a Session or SessionChain record.\u003C/p\u003E\n\u003Cp\u003EPreviously issued JWT access tokens are not automatically invalidated by refresh-token rotation or refresh-chain revocation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-touch\u0022\u003ESession touch\u003C/h2\u003E\n\u003Cp\u003EA session touch is a controlled update to existing server-side authentication state. It does not issue a replacement credential or create a new session.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ESession ID\n \u2192 Validate session, chain and device context\n \u2192 Recheck active state and chain/session relationship\n \u2192 Touch if policy requires\n \u2192 Continue with the same session ID\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn \u003Ccode\u003EPureOpaque\u003C/code\u003E, the refresh flow requires a session ID. The session validator checks the session against the current tenant, device context and session options. The touch service then reloads the session and chain from the store and checks that they are still active and consistent, including the chain\u0027s active session, tenant, user and chain identifiers.\u003C/p\u003E\n\u003Cp\u003ETouch behavior is governed by the effective session options:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchInterval\u003C/code\u003E avoids writing activity state on every request. If the interval has not elapsed, the operation may succeed as \u003Cstrong\u003ENoOp\u003C/strong\u003E.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchMode\u003C/code\u003E is \u003Ccode\u003EIfNeeded\u003C/code\u003E by default; \u003Ccode\u003EForce\u003C/code\u003E requests a touch even when the normal interval has not elapsed.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ESlidingExpiration\u003C/code\u003E allows a touch to extend the session expiration using the configured \u003Ccode\u003ELifetime\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EAn absolute chain expiration remains an upper bound; sliding expiration cannot extend the session beyond it.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EIdleTimeout\u003C/code\u003E participates in chain-state validation. An idle or otherwise inactive chain cannot be revived merely by touching it.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA successful \u003Cstrong\u003ENoOp\u003C/strong\u003E is not a failed refresh: the existing state was valid, but no persistence update was necessary. Likewise, a touch is not an unconditional promise to extend the session\u0027s expiry; that depends on policy and the absolute limit.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-token-rotation\u0022\u003ERefresh-token rotation\u003C/h2\u003E\n\u003Cp\u003ERotation replaces a valid refresh credential while preserving its association with the existing authentication context.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERefresh token\n \u2192 Validate token, tenant, device and expected session (if supplied)\n \u2192 Resolve user, session and chain\n \u2192 Prepare replacement refresh/access tokens\n \u2192 Atomically consume old refresh token and store replacement\n \u2192 Return new credentials\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe rotation service first rejects modes or configurations that do not permit refresh-token issuance (\u003Ccode\u003EPureOpaque\u003C/code\u003E or \u003Ccode\u003EIssueRefresh = false\u003C/code\u003E). It then validates the presented credential and its context. The replacement refresh token and access token are prepared before the existing token is consumed. Persistence uses the refresh-token store\u0027s execution boundary and \u003Ccode\u003ETryConsumeAsync\u003C/code\u003E, so competing requests cannot both successfully consume the same old token.\u003C/p\u003E\n\u003Cp\u003ERotation preserves the validated user, session and chain association; it is \u003Cstrong\u003Enot\u003C/strong\u003E a new authentication or a new session. Claims for the replacement access token are obtained through the configured claims provider.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reuse-and-concurrent-requests\u0022\u003EReuse and concurrent requests\u003C/h3\u003E\n\u003Cp\u003EA consumed refresh token cannot be used again to obtain another replacement. UltimateAuth distinguishes two situations:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ELikely concurrent request:\u003C/strong\u003E if a consumed token has a recorded replacement and the second request falls within \u003Ccode\u003ERefreshTokenConcurrentRequestWindow\u003C/code\u003E, the second rotation is rejected without treating it as a confirmed replay.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReplay outside that window:\u003C/strong\u003E the rotation service revokes the associated refresh-token chain, or tokens associated with the session when a chain identifier is unavailable.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis distinction reduces destructive responses to ordinary client-side concurrency while retaining a response to suspicious reuse. The concurrency window is \u003Cstrong\u003Enot\u003C/strong\u003E a grace period in which the old token may be exchanged again: the second request still fails.\u003C/p\u003E\n\u003Cp\u003EThe rotation implementation shown here revokes refresh-token state. Do not interpret that as an unconditional guarantee that every related server-side session is also revoked; session invalidation is a separate concern.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022how-each-mode-executes\u0022\u003EHow each mode executes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022pureopaque-session-continuation\u0022\u003EPureOpaque: session continuation\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EPureOpaque\u003C/code\u003E has no refresh-token rotation step. The endpoint resolves the existing session from the authentication flow context, validates it and performs a conditional touch. It returns \u003Ccode\u003ETouched\u003C/code\u003E when state was updated or \u003Ccode\u003ENoOp\u003C/code\u003E when the valid session required no update.\u003C/p\u003E\n\u003Cp\u003ENo access token or refresh token is issued. The existing session ID remains the credential representing the continued context.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022hybrid-session-and-token-continuity\u0022\u003EHybrid: session and token continuity\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EHybrid\u003C/code\u003E requires \u003Cstrong\u003Eboth\u003C/strong\u003E a valid session ID and a refresh token. The flow:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates the session and device context.\u003C/li\u003E\n\u003Cli\u003EPerforms the session touch operation according to policy.\u003C/li\u003E\n\u003Cli\u003EValidates and rotates the refresh token, requiring it to match the expected session.\u003C/li\u003E\n\u003Cli\u003EReturns the existing session ID together with replacement access and refresh tokens.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe order is important: \u003Cstrong\u003Esession touch happens before token rotation\u003C/strong\u003E in the current implementation. These operations are not presented as one cross-store transaction. If rotation subsequently fails, the refresh response fails, although a preceding session touch may already have been persisted. This should not be described as an all-or-nothing operation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022request-resolution-and-response-delivery\u0022\u003ERequest resolution and response delivery\u003C/h2\u003E\n\u003Cp\u003EThe refresh endpoint uses the server\u0027s \u003Ccode\u003EAuthFlowContext\u003C/code\u003E. It obtains the session ID from \u003Ccode\u003Eflow.Session\u003C/code\u003E, the device from \u003Ccode\u003Eflow.Device\u003C/code\u003E, and the refresh token through \u003Ccode\u003ERefreshTokenResolver\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor refresh-token input, the resolver checks:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EThe explicit \u003Ccode\u003EX-Refresh-Token\u003C/code\u003E header, if present.\u003C/li\u003E\n\u003Cli\u003EThe configured refresh cookie, when cookie delivery is active.\u003C/li\u003E\n\u003Cli\u003EThe configured refresh header, when header delivery is active.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe explicit header takes precedence. Header values may be supplied with a \u003Ccode\u003EBearer \u003C/code\u003E prefix, which the resolver strips.\u003C/p\u003E\n\u003Cp\u003EOn success, the endpoint chooses a \u003Cstrong\u003Eprimary credential\u003C/strong\u003E according to the refresh response policy, rather than automatically writing every credential returned by the flow. The refresh token is written separately when permitted by the response policy and when a replacement exists. Actual cookie/header placement is determined by the effective response configuration and application profile.\u003C/p\u003E\n\u003Cp\u003EThe HTTP endpoint returns \u003Cstrong\u003E\u003Ccode\u003E204 No Content\u003C/code\u003E\u003C/strong\u003E on successful refresh and \u003Cstrong\u003E\u003Ccode\u003E401 Unauthorized\u003C/code\u003E\u003C/strong\u003E when continuation fails. Clients should obtain credentials from the configured response delivery mechanism rather than expecting a JSON token payload. When \u003Ccode\u003EDiagnostics.EnableRefreshDetails\u003C/code\u003E is enabled, the endpoint also writes the refresh outcome through its diagnostic response writer.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022outcomes-and-client-expectations\u0022\u003EOutcomes and client expectations\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOutcome\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003Cth\u003EClient interpretation\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENoOp\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExisting session is valid; no touch was necessary\u003C/td\u003E\n\u003Ctd\u003EContinue normally\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETouched\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExisting session activity was updated\u003C/td\u003E\n\u003Ctd\u003EContinue normally\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERotated\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh token was consumed and replacement credentials issued\u003C/td\u003E\n\u003Ctd\u003EReplace stored credentials with the new values\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthRequired\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EThe flow could not safely continue\u003C/td\u003E\n\u003Ctd\u003EStop using the failed refresh credential and require authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshFlowResult\u003C/code\u003E also recognizes \u003Ccode\u003ESuccess\u003C/code\u003E as a successful outcome, although the mode-specific branches described above return \u003Ccode\u003ENoOp\u003C/code\u003E, \u003Ccode\u003ETouched\u003C/code\u003E, \u003Ccode\u003ERotated\u003C/code\u003E or \u003Ccode\u003EReauthRequired\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EClients should serialize refresh attempts where practical. Parallel refresh requests using the same token do not produce multiple valid replacements, even when they fall within the concurrency window.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-boundaries\u0022\u003ESecurity boundaries\u003C/h2\u003E\n\u003Cp\u003ERefresh continues existing trust only while the relevant state remains valid:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession and chain checks:\u003C/strong\u003E session-based paths validate active state, tenant, user, chain and session relationships.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EDevice context:\u003C/strong\u003E session and refresh-token validation receive the current device context; mismatches can prevent continuation.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESingle-use refresh tokens:\u003C/strong\u003E successful rotation consumes the old credential and persists a replacement.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReplay response:\u003C/strong\u003E suspicious reuse can revoke refresh-token state associated with the chain or session.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EExpiration:\u003C/strong\u003E idle, session, chain and refresh-token validity rules can end continuation. Refresh does not bypass those limits.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EIssuance policy:\u003C/strong\u003E \u003Ccode\u003EIssueRefresh = false\u003C/code\u003E prevents rotation before the old token is consumed.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese controls complement one another. A refresh token should be treated as a sensitive credential, not as a harmless request to generate another access token.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022summary\u0022\u003ESummary\u003C/h2\u003E\n\u003Cp\u003EThe useful distinction is not simply \u003Cem\u003Estateful versus stateless\u003C/em\u003E. It is \u003Cstrong\u003Ewhat must remain valid for authentication to continue\u003C/strong\u003E:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003EPureOpaque\u003C/code\u003E continues an existing server-side session, with conditional activity updates.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EHybrid\u003C/code\u003E requires both session validity and successful refresh-token rotation.\u003C/li\u003E\n\u003Cli\u003EOther rotation branches exist, but are not part of the completed v0.1.0 supported-mode set.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ERefresh does not authenticate a user again. It extends the usefulness of an already established authentication context only within the boundaries of the selected mode and configured security policies.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-step\u0022\u003ENext step\u003C/h2\u003E\n\u003Cp\u003EContinue to \u003Ca href=\u0022./logout-flow\u0022\u003ELogout Flow\u003C/a\u003E.\u003C/p\u003E\n", + "Html": "\n\u003Cp\u003ERefresh is how an existing authentication context continues without asking the user to authenticate again. In UltimateAuth, it is not synonymous with issuing a new access token: the operation depends on the active authentication mode and on whether the context is represented by a server-side session, refresh credentials, or both.\u003C/p\u003E\n\u003Cp\u003EA successful refresh preserves the authenticated identity and its continuity. It does \u003Cstrong\u003Enot\u003C/strong\u003E prove the user\u0027s credentials again, create a new login, or necessarily extend every lifetime associated with the authentication.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003EThis guide describes server-side refresh execution.\u003C/p\u003E\n\u003Cp\u003EFor client-side scheduling, proactive renewal, reactive recovery, background refresh, and concurrent request coordination, see \u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-model-continuity-not-a-second-login\u0022\u003EThe model: continuity, not a second login\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth distinguishes three related operations:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthentication\u003C/strong\u003E establishes a new authenticated context after the required proof is accepted.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ERefresh\u003C/strong\u003E attempts to continue an already established context, subject to its current validity and security policies.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReauthentication\u003C/strong\u003E establishes trust again when continuation is unavailable or no longer permitted.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis distinction matters for both security and client behavior. A refresh request can fail because a session expired, a refresh credential is invalid or consumed, the device context does not match, or the underlying chain is no longer usable. The client should treat an unsuccessful refresh as a need to authenticate again, not as an invitation to retry the same credential indefinitely.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022mode-dependent-strategies\u0022\u003EMode-dependent strategies\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EContinuation mechanism\u003C/th\u003E\n\u003Cth\u003ERequired state\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque\u003C/td\u003E\n\u003Ctd\u003ESession touch\u003C/td\u003E\n\u003Ctd\u003EValid server-side session\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid\u003C/td\u003E\n\u003Ctd\u003ESession-backed refresh-token rotation\u003C/td\u003E\n\u003Ctd\u003EValid session and refresh token\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESemiHybrid\u003C/td\u003E\n\u003Ctd\u003EPlanned\u003C/td\u003E\n\u003Ctd\u003ENot currently supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureJwt\u003C/td\u003E\n\u003Ctd\u003ERefresh-token rotation\u003C/td\u003E\n\u003Ctd\u003EValid refresh token and refresh chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt-refresh-without-a-session\u0022\u003EPureJwt: refresh without a session\u003C/h3\u003E\n\u003Cp\u003EPureJwt uses a persisted refresh-token chain without requiring an authentication session.\u003C/p\u003E\n\u003Cp\u003EThe refresh operation:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates the refresh token, tenant, and device binding.\u003C/li\u003E\n\u003Cli\u003EVerifies that the token is associated with a valid refresh chain and is not session-bound.\u003C/li\u003E\n\u003Cli\u003EResolves the authenticated user\u0027s current identity information and claims.\u003C/li\u003E\n\u003Cli\u003EGenerates replacement access and refresh credentials.\u003C/li\u003E\n\u003Cli\u003EAtomically consumes the previous refresh token and persists its replacement.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe new JWT access token can be validated independently by Resource APIs.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022concurrent-requests-and-replay-protection\u0022\u003EConcurrent requests and replay protection\u003C/h3\u003E\n\u003Cp\u003EA consumed refresh token cannot be used for another successful rotation.\u003C/p\u003E\n\u003Cp\u003EThe configured concurrent-request window distinguishes likely overlapping refresh requests from later reuse attempts.\u003C/p\u003E\n\u003Cp\u003EReuse outside that window can revoke the associated refresh chain.\u003C/p\u003E\n\u003Cp\u003EFor PureJwt, this revocation does not require a Session or SessionChain record.\u003C/p\u003E\n\u003Cp\u003EPreviously issued JWT access tokens are not automatically invalidated by refresh-token rotation or refresh-chain revocation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-touch\u0022\u003ESession touch\u003C/h2\u003E\n\u003Cp\u003EA session touch is a controlled update to existing server-side authentication state. It does not issue a replacement credential or create a new session.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ESession ID\n \u2192 Validate session, chain and device context\n \u2192 Recheck active state and chain/session relationship\n \u2192 Touch if policy requires\n \u2192 Continue with the same session ID\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn \u003Ccode\u003EPureOpaque\u003C/code\u003E, the refresh flow requires a session ID. The session validator checks the session against the current tenant, device context and session options. The touch service then reloads the session and chain from the store and checks that they are still active and consistent, including the chain\u0027s active session, tenant, user and chain identifiers.\u003C/p\u003E\n\u003Cp\u003ETouch behavior is governed by the effective session options:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchInterval\u003C/code\u003E avoids writing activity state on every request. If the interval has not elapsed, the operation may succeed as \u003Cstrong\u003ENoOp\u003C/strong\u003E.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchMode\u003C/code\u003E is \u003Ccode\u003EIfNeeded\u003C/code\u003E by default; \u003Ccode\u003EForce\u003C/code\u003E requests a touch even when the normal interval has not elapsed.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ESlidingExpiration\u003C/code\u003E allows a touch to extend the session expiration using the configured \u003Ccode\u003ELifetime\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EAn absolute chain expiration remains an upper bound; sliding expiration cannot extend the session beyond it.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EIdleTimeout\u003C/code\u003E participates in chain-state validation. An idle or otherwise inactive chain cannot be revived merely by touching it.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA successful \u003Cstrong\u003ENoOp\u003C/strong\u003E is not a failed refresh: the existing state was valid, but no persistence update was necessary. Likewise, a touch is not an unconditional promise to extend the session\u0027s expiry; that depends on policy and the absolute limit.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-token-rotation\u0022\u003ERefresh-token rotation\u003C/h2\u003E\n\u003Cp\u003ERotation replaces a valid refresh credential while preserving its association with the existing authentication context.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERefresh token\n \u2192 Validate token, tenant, device and expected session (if supplied)\n \u2192 Resolve user, session and chain\n \u2192 Prepare replacement refresh/access tokens\n \u2192 Atomically consume old refresh token and store replacement\n \u2192 Return new credentials\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe rotation service first rejects modes or configurations that do not permit refresh-token issuance (\u003Ccode\u003EPureOpaque\u003C/code\u003E or \u003Ccode\u003EIssueRefresh = false\u003C/code\u003E). It then validates the presented credential and its context. The replacement refresh token and access token are prepared before the existing token is consumed. Persistence uses the refresh-token store\u0027s execution boundary and \u003Ccode\u003ETryConsumeAsync\u003C/code\u003E, so competing requests cannot both successfully consume the same old token.\u003C/p\u003E\n\u003Cp\u003ERotation preserves the validated user, session and chain association; it is \u003Cstrong\u003Enot\u003C/strong\u003E a new authentication or a new session. Claims for the replacement access token are obtained through the configured claims provider.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reuse-and-concurrent-requests\u0022\u003EReuse and concurrent requests\u003C/h3\u003E\n\u003Cp\u003EA consumed refresh token cannot be used again to obtain another replacement. UltimateAuth distinguishes two situations:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ELikely concurrent request:\u003C/strong\u003E if a consumed token has a recorded replacement and the second request falls within \u003Ccode\u003ERefreshTokenConcurrentRequestWindow\u003C/code\u003E, the second rotation is rejected without treating it as a confirmed replay.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReplay outside that window:\u003C/strong\u003E the rotation service revokes the associated refresh-token chain, or tokens associated with the session when a chain identifier is unavailable.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis distinction reduces destructive responses to ordinary client-side concurrency while retaining a response to suspicious reuse. The concurrency window is \u003Cstrong\u003Enot\u003C/strong\u003E a grace period in which the old token may be exchanged again: the second request still fails.\u003C/p\u003E\n\u003Cp\u003EThe rotation implementation shown here revokes refresh-token state. Do not interpret that as an unconditional guarantee that every related server-side session is also revoked; session invalidation is a separate concern.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022how-each-mode-executes\u0022\u003EHow each mode executes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022pureopaque-session-continuation\u0022\u003EPureOpaque: session continuation\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EPureOpaque\u003C/code\u003E has no refresh-token rotation step. The endpoint resolves the existing session from the authentication flow context, validates it and performs a conditional touch. It returns \u003Ccode\u003ETouched\u003C/code\u003E when state was updated or \u003Ccode\u003ENoOp\u003C/code\u003E when the valid session required no update.\u003C/p\u003E\n\u003Cp\u003ENo access token or refresh token is issued. The existing session ID remains the credential representing the continued context.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022hybrid-session-and-token-continuity\u0022\u003EHybrid: session and token continuity\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EHybrid\u003C/code\u003E requires \u003Cstrong\u003Eboth\u003C/strong\u003E a valid session ID and a refresh token. The flow:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates the session and device context.\u003C/li\u003E\n\u003Cli\u003EPerforms the session touch operation according to policy.\u003C/li\u003E\n\u003Cli\u003EValidates and rotates the refresh token, requiring it to match the expected session.\u003C/li\u003E\n\u003Cli\u003EReturns the existing session ID together with replacement access and refresh tokens.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe order is important: \u003Cstrong\u003Esession touch happens before token rotation\u003C/strong\u003E in the current implementation. These operations are not presented as one cross-store transaction. If rotation subsequently fails, the refresh response fails, although a preceding session touch may already have been persisted. This should not be described as an all-or-nothing operation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022request-resolution-and-response-delivery\u0022\u003ERequest resolution and response delivery\u003C/h2\u003E\n\u003Cp\u003EThe refresh endpoint uses the server\u0027s \u003Ccode\u003EAuthFlowContext\u003C/code\u003E. It obtains the session ID from \u003Ccode\u003Eflow.Session\u003C/code\u003E, the device from \u003Ccode\u003Eflow.Device\u003C/code\u003E, and the refresh token through \u003Ccode\u003ERefreshTokenResolver\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor refresh-token input, the resolver checks:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EThe explicit \u003Ccode\u003EX-Refresh-Token\u003C/code\u003E header, if present.\u003C/li\u003E\n\u003Cli\u003EThe configured refresh cookie, when cookie delivery is active.\u003C/li\u003E\n\u003Cli\u003EThe configured refresh header, when header delivery is active.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe explicit header takes precedence. Header values may be supplied with a \u003Ccode\u003EBearer \u003C/code\u003E prefix, which the resolver strips.\u003C/p\u003E\n\u003Cp\u003EOn success, the endpoint chooses a \u003Cstrong\u003Eprimary credential\u003C/strong\u003E according to the refresh response policy, rather than automatically writing every credential returned by the flow. The refresh token is written separately when permitted by the response policy and when a replacement exists. Actual cookie/header placement is determined by the effective response configuration and application profile.\u003C/p\u003E\n\u003Cp\u003EThe HTTP endpoint returns \u003Cstrong\u003E\u003Ccode\u003E204 No Content\u003C/code\u003E\u003C/strong\u003E on successful refresh and \u003Cstrong\u003E\u003Ccode\u003E401 Unauthorized\u003C/code\u003E\u003C/strong\u003E when continuation fails. Clients should obtain credentials from the configured response delivery mechanism rather than expecting a JSON token payload. When \u003Ccode\u003EDiagnostics.EnableRefreshDetails\u003C/code\u003E is enabled, the endpoint also writes the refresh outcome through its diagnostic response writer.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022outcomes-and-client-expectations\u0022\u003EOutcomes and client expectations\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOutcome\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003Cth\u003EClient interpretation\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENoOp\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExisting session is valid; no touch was necessary\u003C/td\u003E\n\u003Ctd\u003EContinue normally\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETouched\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExisting session activity was updated\u003C/td\u003E\n\u003Ctd\u003EContinue normally\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERotated\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh token was consumed and replacement credentials issued\u003C/td\u003E\n\u003Ctd\u003EReplace stored credentials with the new values\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthRequired\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EThe flow could not safely continue\u003C/td\u003E\n\u003Ctd\u003EStop using the failed refresh credential and require authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshFlowResult\u003C/code\u003E also recognizes \u003Ccode\u003ESuccess\u003C/code\u003E as a successful outcome, although the mode-specific branches described above return \u003Ccode\u003ENoOp\u003C/code\u003E, \u003Ccode\u003ETouched\u003C/code\u003E, \u003Ccode\u003ERotated\u003C/code\u003E or \u003Ccode\u003EReauthRequired\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe UltimateAuth Client SDK coordinates refresh attempts through a shared single-flight mechanism within the current client scope.\u003C/p\u003E\n\u003Cp\u003ECustom clients should implement appropriate refresh coordination to avoid unnecessary concurrent rotation attempts.\u003C/p\u003E\n\u003Cp\u003EServer-side rotation and replay protection remain necessary across independent client scopes, applications, and devices.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-boundaries\u0022\u003ESecurity boundaries\u003C/h2\u003E\n\u003Cp\u003ERefresh continues existing trust only while the relevant state remains valid:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession and chain checks:\u003C/strong\u003E session-based paths validate active state, tenant, user, chain and session relationships.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EDevice context:\u003C/strong\u003E session and refresh-token validation receive the current device context; mismatches can prevent continuation.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESingle-use refresh tokens:\u003C/strong\u003E successful rotation consumes the old credential and persists a replacement.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EReplay response:\u003C/strong\u003E suspicious reuse can revoke refresh-token state associated with the chain or session.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EExpiration:\u003C/strong\u003E idle, session, chain and refresh-token validity rules can end continuation. Refresh does not bypass those limits.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EIssuance policy:\u003C/strong\u003E \u003Ccode\u003EIssueRefresh = false\u003C/code\u003E prevents rotation before the old token is consumed.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese controls complement one another. A refresh token should be treated as a sensitive credential, not as a harmless request to generate another access token.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022summary\u0022\u003ESummary\u003C/h2\u003E\n\u003Cp\u003EThe useful distinction is not simply \u003Cem\u003Estateful versus stateless\u003C/em\u003E. It is \u003Cstrong\u003Ewhat must remain valid for authentication to continue\u003C/strong\u003E:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003EPureOpaque\u003C/code\u003E continues an existing server-side session, with conditional activity updates.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EHybrid\u003C/code\u003E requires session validity and successful refresh-token rotation.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ESemiHybrid\u003C/code\u003E describes JWT renewal with server-managed lifecycle state.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EPureJwt\u003C/code\u003E rotates refresh credentials through a session-independent refresh chain.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ERefresh does not authenticate a user again. It extends the usefulness of an already established authentication context only within the boundaries of the selected mode and configured security policies.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-step\u0022\u003ENext step\u003C/h2\u003E\n\u003Cp\u003EContinue to \u003Ca href=\u0022./logout-flow\u0022\u003ELogout Flow\u003C/a\u003E.\u003C/p\u003E\n", "Headings": [ { "Id": "the-model-continuity-not-a-second-login", @@ -79,6 +79,6 @@ "Level": 0 } ], - "SourceHash": "287AA7F1BE0EB954F3A9C8901150A29CA679AC6E3B7A0043F61062550DC3617D", + "SourceHash": "C7D7CDA5FC60BA8FAE4BF3FD6051D8C315BB63FE9C1BD4ED418CA604486577D3", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authentication.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authentication.json index ec886299..d261dd01 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authentication.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authentication.json @@ -1,7 +1,7 @@ { "Slug": "client-sdk/authentication", "Title": "Authentication", - "Html": "\n\u003Cp\u003EThe UltimateAuth Client SDK provides a high-level API for authentication workflows, including login, PKCE, session validation, refresh, logout, and device-specific session revocation.\u003C/p\u003E\n\u003Cp\u003EThese operations are exposed through \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E, which implements the \u003Ccode\u003EIFlowClient\u003C/code\u003E contract.\u003C/p\u003E\n\u003Cp\u003EThis guide shows how to use the authentication client in application code, handle structured results, configure interactive behavior, and choose the correct flow for different client environments.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022accessing-the-authentication-client\u0022\u003E1. Accessing the Authentication Client\u003C/h2\u003E\n\u003Cp\u003EIn a Blazor component, inject \u003Ccode\u003EIUAuthClient\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAuthentication operations are available through the \u003Ccode\u003EFlows\u003C/code\u003E property.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.RefreshAsync();\nawait UAuthClient.Flows.ValidateAsync();\nawait UAuthClient.Flows.LogoutAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe relevant methods are defined by \u003Ccode\u003EIFlowClient\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMethod\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmit a direct login flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAttempt login with configurable try/commit behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBeginPkceAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EStart a PKCE authentication flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECompletePkceLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EComplete a PKCE login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryCompletePkceLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EComplete PKCE with structured try/commit behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh or continue authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidateAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EValidate current authentication state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELog out the current session\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutMyDeviceAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke a selected device-associated chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutMyOtherDevicesAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke other devices while retaining the current one\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutAllMyDevicesAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke all devices for the current user\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EAdministrative device logout operations are also available and covered later in this guide.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022choosing-the-correct-login-flow\u0022\u003E2. Choosing the Correct Login Flow\u003C/h2\u003E\n\u003Cp\u003EBefore implementing login, determine whether your application is a trusted server-hosted client or a public client.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient environment\u003C/th\u003E\n\u003Cth\u003ERecommended flow\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBlazor Server\u003C/td\u003E\n\u003Ctd\u003EDirect login or supported interactive login flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EUAuthHub\u003C/td\u003E\n\u003Ctd\u003EServer-hosted authentication flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBlazor WebAssembly\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBrowser SPA\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPublic native application\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EPublic clients must not rely on embedding a secret or trusting browser-executed code to protect credentials.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth restricts direct credential posting based on the configured application profile and login options.\u003C/p\u003E\n\u003Cp\u003EFor public clients, use the PKCE flow instead of enabling direct credential posting.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-login\u0022\u003E3. Direct Login\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E performs a direct login submission.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LoginRequest\n{\n Identifier = \u0026quot;user@example.com\u0026quot;,\n Secret = \u0026quot;password\u0026quot;\n};\n\nawait UAuthClient.Flows.LoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E returns a structured login result describing the outcome of the submission.\u003C/p\u003E\n\u003Cp\u003EThe client discovers the effective login transport supported by the server.\u003C/p\u003E\n\u003Cp\u003EDepending on the authentication mode, credential delivery configuration, and return URL, login may use browser navigation or a fetch-based request.\u003C/p\u003E\n\u003Cp\u003EA navigation submission does not itself confirm successful server-side authentication. A fetch-based submission allows the client to observe the server response and process delivered credentials.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022login-transport-selection\u0022\u003ELogin Transport Selection\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth supports three login transport strategies:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ETransport\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically selects a compatible transport\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENavigation\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits the login through browser navigation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EFetch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits the login through an HTTP request and processes the response\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EAuto\u003C/code\u003E is the default and recommended strategy.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LoginAsync(\n request,\n returnUrl: \u0026quot;/dashboard\u0026quot;,\n transport: UAuthLoginTransport.Auto);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENavigation is suitable when the effective credential delivery configuration supports browser-managed authentication credentials.\u003C/p\u003E\n\u003Cp\u003EFetch is required when the client must observe a header-delivered access token.\u003C/p\u003E\n\u003Cp\u003EApplications can explicitly request fetch-based login:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LoginAsync(\n request,\n transport: UAuthLoginTransport.Fetch);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAn explicitly requested transport must be compatible with the effective server configuration.\u003C/p\u003E\n\u003Cp\u003EThe client does not silently downgrade an incompatible explicit navigation request.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022processing-header-delivered-access-tokens\u0022\u003EProcessing Header-Delivered Access Tokens\u003C/h3\u003E\n\u003Cp\u003EWhen login delivers an access token through a response header, UltimateAuth processes the token and stores it in the client-side token store.\u003C/p\u003E\n\u003Cp\u003EThe default token store is in-memory.\u003C/p\u003E\n\u003Cp\u003EApplications using the UltimateAuth client do not need to manually extract JWTs from login responses or construct authorization headers.\u003C/p\u003E\n\u003Cp\u003EThe client attaches the access token to supported authenticated requests and clears expired credentials from the token store.\u003C/p\u003E\n\u003Cp\u003EIn-memory storage does not persist access tokens across a full application reload.\u003C/p\u003E\n\u003Cp\u003EAuthentication continuation after a reload depends on the available refresh credential and the effective server configuration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022loginrequest-properties\u0022\u003ELoginRequest Properties\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginRequest\u003C/code\u003E supports the following properties:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIdentifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESecret\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECredential secret\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECredentialType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECredential type; defaults to \u003Ccode\u003EPassword\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMetadata\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional request metadata\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERequestTokens\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EHint to request tokens when supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPreviewReceipt\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional receipt associated with a prior login preview\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EExample:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LoginRequest\n{\n Identifier = email,\n Secret = password,\n CredentialType = CredentialType.Password,\n RequestTokens = true\n};\n\nawait UAuthClient.Flows.LoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ERequestTokens\u003C/code\u003E is a hint, not a guarantee that tokens will be issued. The server\u0027s authentication mode and policy remain authoritative.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect-after-login\u0022\u003ERedirect After Login\u003C/h3\u003E\n\u003Cp\u003EProvide an explicit return URL when necessary:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.LoginAsync(request, returnUrl: \u0026quot;/dashboard\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe direct login flow resolves its return URL in the following order:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EThe explicit \u003Ccode\u003EreturnUrl\u003C/code\u003E argument.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E option.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E option.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EFor example, client options can specify a default:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe return URL is part of the login workflow. It should not be treated as an authorization grant.\u003C/p\u003E\n\u003Cp\u003EApplications and servers must still enforce their redirect validation rules.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-login-with-tryloginasync\u0022\u003E4. Interactive Login with TryLoginAsync\u003C/h2\u003E\n\u003Cp\u003EFor interactive forms, \u003Ccode\u003ETryLoginAsync\u003C/code\u003E provides structured feedback before or during the authentication commit process.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryAndCommit);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is generally the more useful API for a login form that needs to display validation feedback.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submit-modes\u0022\u003ESubmit Modes\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthSubmitMode\u003C/code\u003E defines three submission behaviors.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExecute the try operation and return its result without committing authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmit directly to the commit endpoint without a separate try operation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETry first, then commit when the try operation succeeds\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese modes control client workflow, not whether the server validates authentication.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EDirectCommit does not bypass credential verification or server security requirements.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022tryonly-validate-without-login\u0022\u003ETryOnly: Validate Without Login\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ETryOnly\u003C/code\u003E when you want structured feedback without establishing an authenticated session.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryOnly);\n\nif (result.IsSuccess)\n{\n // The try operation succeeded.\n // Authentication has not been committed.\n}\nelse\n{\n // Display the appropriate feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis can be useful for a custom interactive workflow.\u003C/p\u003E\n\u003Cp\u003EA successful try result must not be interpreted as an authenticated application session.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022tryandcommit-interactive-login\u0022\u003ETryAndCommit: Interactive Login\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ETryAndCommit\u003C/code\u003E to combine structured validation with authentication commit.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryAndCommit,\n returnUrl: \u0026quot;/dashboard\u0026quot;);\n\nif (!result.IsSuccess)\n{\n // Show validation feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the try stage succeeds, the client proceeds to the commit operation through its configured transport.\u003C/p\u003E\n\u003Cp\u003EThis can involve navigation, so application code should not assume that execution always continues within the same component instance.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022directcommit-single-commit-submission\u0022\u003EDirectCommit: Single Commit Submission\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.DirectCommit);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn this mode, the SDK submits the commit operation directly.\u003C/p\u003E\n\u003Cp\u003EThe method returns a \u003Ccode\u003ETryLoginResult\u003C/code\u003E with \u003Ccode\u003EIsSuccess = true\u003C/code\u003E after the navigation submission completes, but this is not a structured server-side authentication success confirmation.\u003C/p\u003E\n\u003Cp\u003EIf you need structured credential validation feedback, prefer \u003Ccode\u003ETryAndCommit\u003C/code\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-login-results\u0022\u003E5. Handling Login Results\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ETryLoginAsync\u003C/code\u003E returns \u003Ccode\u003ETryLoginResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EIts available properties include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsSuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether the try operation succeeded\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReason\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional authentication failure reason\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERemainingAttempts\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERemaining attempts, when provided\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELockoutUntilUtc\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELockout expiration, when provided\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERequiresMfa\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether additional authentication is required\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPreviewReceipt\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional receipt for subsequent flow handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EExample:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(request, UAuthSubmitMode.TryOnly);\n\nif (!result.IsSuccess)\n{\n if (result.LockoutUntilUtc is not null)\n {\n errorMessage = $\u0026quot;Login temporarily unavailable until {result.LockoutUntilUtc:u}\u0026quot;;\n }\n else\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n\n return;\n}\n\nif (result.RequiresMfa)\n{\n // Continue with the supported additional authentication flow.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDo not expose sensitive internal authentication details unnecessarily.\u003C/p\u003E\n\u003Cp\u003EFor public-facing login forms, generic failure messages may be preferable to displaying every failure reason.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-transport-and-protocol-errors\u0022\u003EHandling Transport and Protocol Errors\u003C/h3\u003E\n\u003Cp\u003EA structured authentication failure is different from a network or protocol failure.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Etry\n{\n var result = await UAuthClient.Flows.TryLoginAsync(request, UAuthSubmitMode.TryAndCommit);\n\n if (!result.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n}\ncatch (UAuthTransportException)\n{\n errorMessage = \u0026quot;Authentication service is unavailable.\u0026quot;;\n}\ncatch (UAuthProtocolException)\n{\n errorMessage = \u0026quot;An authentication protocol error occurred.\u0026quot;;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUse the corresponding UltimateAuth client error namespace when referencing these exception types.\u003C/p\u003E\n\u003Cp\u003EA failed authentication attempt should normally be handled through the structured try result where supported. Transport and protocol exceptions indicate different failure categories.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022pkce-authentication\u0022\u003E6. PKCE Authentication\u003C/h2\u003E\n\u003Cp\u003EPKCE provides a proof mechanism for authorization-code-based authentication flows.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth supports PKCE using an S256 code challenge.\u003C/p\u003E\n\u003Cp\u003EThe SDK generates a cryptographically random verifier, derives its challenge, and coordinates the authorization flow.\u003C/p\u003E\n\u003Cp\u003EPublic clients such as Blazor WebAssembly should use PKCE rather than direct credential posting.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022start-pkce\u0022\u003EStart PKCE\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.BeginPkceAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EYou can provide a return URL:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.BeginPkceAsync(returnUrl: \u0026quot;/dashboard\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client performs the following operations:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EGenerates a PKCE code verifier.\u003C/li\u003E\n\u003Cli\u003EDerives an S256 code challenge.\u003C/li\u003E\n\u003Cli\u003ESends the authorization request.\u003C/li\u003E\n\u003Cli\u003EReceives an authorization code.\u003C/li\u003E\n\u003Cli\u003EInvokes the configured authorization callback, if any.\u003C/li\u003E\n\u003Cli\u003ENavigates to the configured UAuthHub login flow when automatic redirection is enabled.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe authorization code and verifier are used later to complete the flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-pkce\u0022\u003EConfigure PKCE\u003C/h3\u003E\n\u003Cp\u003EThe relevant client options include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.Enabled = true;\noptions.Pkce.AutoRedirect = true;\noptions.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EPKCE is enabled by default in \u003Ccode\u003EUAuthClientPkceLoginFlowOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EAutomatic redirection is also enabled by default.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022observe-authorization\u0022\u003EObserve Authorization\u003C/h3\u003E\n\u003Cp\u003EYou can register a callback that runs after the authorization code is received and before the automatic Hub redirect.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.OnAuthorized = async response =\u0026gt;\n{\n // Observe the authorization response.\n await Task.CompletedTask;\n};\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis callback is useful for application-specific coordination.\u003C/p\u003E\n\u003Cp\u003EDo not log authorization codes or expose them to unrelated components.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disable-automatic-redirection\u0022\u003EDisable Automatic Redirection\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AutoRedirect = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith this configuration, \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E still performs the authorization request and invokes \u003Ccode\u003EOnAuthorized\u003C/code\u003E, but it does not automatically navigate to the Hub login endpoint.\u003C/p\u003E\n\u003Cp\u003EThe application becomes responsible for coordinating the remaining flow.\u003C/p\u003E\n\u003Cp\u003EThis is an advanced integration option.\u003C/p\u003E\n\u003Cp\u003EA custom implementation must preserve the authorization code, verifier, and relevant context securely and complete the flow using the supported protocol.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-pkce-login\u0022\u003E7. Complete PKCE Login\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ECompletePkceLoginAsync\u003C/code\u003E submits the PKCE completion request.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new PkceCompleteRequest\n{\n AuthorizationCode = authorizationCode,\n CodeVerifier = codeVerifier,\n Identifier = email,\n Secret = password,\n ReturnUrl = \u0026quot;/dashboard\u0026quot;\n};\n\nawait UAuthClient.Flows.CompletePkceLoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe request model includes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuthorizationCode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECode obtained from the authorization step\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECodeVerifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOriginal PKCE verifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIdentifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESecret\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin credential\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional post-login destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional Hub session context\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe authorization code and verifier must correspond to the same PKCE flow.\u003C/p\u003E\n\u003Cp\u003EDo not generate a new verifier when completing an existing authorization.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-pkce-completion\u0022\u003EInteractive PKCE Completion\u003C/h3\u003E\n\u003Cp\u003EFor structured feedback, use \u003Ccode\u003ETryCompletePkceLoginAsync\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryCompletePkceLoginAsync(\n request,\n UAuthSubmitMode.TryAndCommit);\n\nif (!result.IsSuccess)\n{\n // Display PKCE login feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe same submit modes are supported:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022try-pkce-without-commit\u0022\u003ETry PKCE Without Commit\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryCompletePkceLoginAsync(request, UAuthSubmitMode.TryOnly);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis returns a \u003Ccode\u003ETryPkceLoginResult\u003C/code\u003E without committing a successful login.\u003C/p\u003E\n\u003Cp\u003EThe result includes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eresult.IsSuccess;\nresult.Reason;\nresult.RemainingAttempts;\nresult.LockoutUntilUtc;\nresult.RequiresMfa;\nresult.RetryWithNewPkce;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022retrywithnewpkce\u0022\u003ERetryWithNewPkce\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERetryWithNewPkce\u003C/code\u003E indicates that the client should begin a new PKCE authorization sequence rather than continuing with the existing authorization material.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eif (result.RetryWithNewPkce)\n{\n await UAuthClient.Flows.BeginPkceAsync(\u0026quot;/login\u0026quot;);\n return;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is useful when the current PKCE context can no longer be used.\u003C/p\u003E\n\u003Cp\u003EThe application should not repeatedly resubmit the same invalid authorization code and verifier.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022uauthhub-handoff-and-credential-ownership\u0022\u003EUAuthHub Handoff and Credential Ownership\u003C/h3\u003E\n\u003Cp\u003EA PKCE flow initiated by an application retains the initiating application\u0027s authentication context.\u003C/p\u003E\n\u003Cp\u003EWhen the user completes login through UAuthHub, the resulting credentials belong to the initiating application, not to the Hub\u0027s interactive login interface.\u003C/p\u003E\n\u003Cp\u003EThe Hub completes the authentication flow and returns the user to the validated application return URL.\u003C/p\u003E\n\u003Cp\u003EHeader-delivered access tokens associated with the initiating application must not be installed into the Hub\u0027s local authentication state.\u003C/p\u003E\n\u003Cp\u003EAfter returning to the initiating application, the client can restore authentication through the available session or refresh credentials.\u003C/p\u003E\n\u003Cp\u003EThis behavior preserves the original application and device context throughout the authentication journey.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-recovery\u0022\u003EAuthentication Recovery\u003C/h3\u003E\n\u003Cp\u003EThe client may recover a header-delivered access token when the application starts without a usable token but a compatible refresh credential remains available.\u003C/p\u003E\n\u003Cp\u003EThis allows authentication to continue after a full application reload or a supported UAuthHub handoff.\u003C/p\u003E\n\u003Cp\u003ERecovery does not bypass refresh-token validation, device binding, expiration, rotation, or server-side authentication policies.\u003C/p\u003E\n\u003Cp\u003ERecovery can fail when the refresh credential has expired, has been revoked, or is unavailable because of browser cookie restrictions.\u003C/p\u003E\n\u003Cp\u003ECross-site browser deployments must not assume that refresh cookies will always be available.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-credential-posting-restrictions\u0022\u003E8. Direct Credential Posting Restrictions\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth restricts direct credential posting according to the configured application profile.\u003C/p\u003E\n\u003Cp\u003EThe client option is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is the default.\u003C/p\u003E\n\u003Cp\u003EIf the current profile is not permitted to post credentials directly and the option has not enabled that capability, direct login methods throw an \u003Ccode\u003EInvalidOperationException\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor example, attempting direct login from a public client may produce an error indicating that PKCE is required.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022trusted-server-hosted-clients\u0022\u003ETrusted Server-Hosted Clients\u003C/h3\u003E\n\u003Cp\u003EThe option can be explicitly configured for a trusted server-hosted integration where direct credential posting is appropriate:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis must not be used to bypass PKCE requirements in a public browser application.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EDo not enable direct credential posting in production Blazor WebAssembly or SPA clients.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EAn application profile is an integration descriptor, not cryptographic proof that the caller is trusted.\u003C/p\u003E\n\u003Cp\u003EServer-side security requirements remain authoritative.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-authentication\u0022\u003E9. Refresh Authentication\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E requests continuation of the current authentication state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method returns \u003Ccode\u003ERefreshResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Epublic sealed record RefreshResult\n{\n public bool IsSuccess { get; init; }\n public int Status { get; init; }\n public RefreshOutcome Outcome { get; init; }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ERefresh behavior depends on the authentication mode.\u003C/p\u003E\n\u003Cp\u003EA refresh operation may update session activity, rotate authentication material, or determine that reauthentication is required.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-refresh-results\u0022\u003EHandling Refresh Results\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\nif (result.IsSuccess)\n{\n // Authentication continuation succeeded.\n}\nelse if (result.Outcome == RefreshOutcome.ReauthRequired)\n{\n // The current authentication can no longer continue.\n // Direct the user to the appropriate login flow.\n}\nelse\n{\n // Handle another unsuccessful refresh result.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EA \u003Ccode\u003E401 Unauthorized\u003C/code\u003E refresh response is handled as a normal reauthentication outcome.\u003C/p\u003E\n\u003Cp\u003EIt returns:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Enew RefreshResult\n{\n IsSuccess = false,\n Status = 401,\n Outcome = RefreshOutcome.ReauthRequired\n};\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENetwork and unexpected protocol failures can still produce exceptions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-outcomes\u0022\u003ERefresh Outcomes\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshOutcome\u003C/code\u003E defines the following values:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOutcome\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ENo specific semantic outcome\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGeneric successful refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENoOp\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ENo refresh state change was necessary\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETouched\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApplicable session activity was updated\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERotated\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERotation occurred\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthRequired\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication continuation is no longer permitted\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\nif (!result.IsSuccess)\n{\n return;\n}\n\nswitch (result.Outcome)\n{\n case RefreshOutcome.Rotated:\n // Authentication material was rotated.\n break;\n\n case RefreshOutcome.Touched:\n // Applicable session activity was updated.\n break;\n\n case RefreshOutcome.NoOp:\n // Successful refresh and no state change was required.\n break;\n\n case RefreshOutcome.Success:\n // Refresh succeeded without a more specific outcome.\n break;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022detailed-refresh-diagnostics\u0022\u003EDetailed Refresh Diagnostics\u003C/h3\u003E\n\u003Cp\u003EThe server may return a generic success outcome rather than exposing the internal refresh action.\u003C/p\u003E\n\u003Cp\u003EWhere supported, detailed refresh outcomes can be enabled through server diagnostics:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Diagnostics.EnableRefreshDetails = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis setting is intended for diagnostics and observability.\u003C/p\u003E\n\u003Cp\u003EApplications should not require a specific successful outcome such as \u003Ccode\u003ERotated\u003C/code\u003E or \u003Ccode\u003ETouched\u003C/code\u003E to consider refresh successful.\u003C/p\u003E\n\u003Cp\u003EUse \u003Ccode\u003EIsSuccess\u003C/code\u003E for the primary success decision.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-and-automatic-refresh\u0022\u003EManual and Automatic Refresh\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E has an optional \u003Ccode\u003EisAuto\u003C/code\u003E argument.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Manual refresh\nawait UAuthClient.Flows.RefreshAsync();\n\n// Refresh initiated by automatic coordination\nawait UAuthClient.Flows.RefreshAsync(isAuto: true);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe parameter distinguishes automatic refresh activity for client diagnostics.\u003C/p\u003E\n\u003Cp\u003EIt does not select a different authentication mode or override the server\u0027s refresh policy.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh-configuration\u0022\u003E10. Automatic Refresh Configuration\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth exposes client-side automatic refresh options through \u003Ccode\u003EAutoRefresh\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Enabled = true;\noptions.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EEnabled\u003C/code\u003E controls background refresh coordination.\u003C/p\u003E\n\u003Cp\u003E\u003Ccode\u003EInterval\u003C/code\u003E specifies the interval used for background refresh attempts.\u003C/p\u003E\n\u003Cp\u003EThe effective defaults and registration behavior depend on the client integration. The options documentation identifies Blazor Server as the environment where background refresh is enabled by default.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh-is-not-a-security-guarantee\u0022\u003EAutomatic Refresh Is Not a Security Guarantee\u003C/h3\u003E\n\u003Cp\u003EAutomatic refresh is a client-side convenience mechanism.\u003C/p\u003E\n\u003Cp\u003EIt does not guarantee that a session will remain valid indefinitely.\u003C/p\u003E\n\u003Cp\u003EAuthentication may still end because of:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EExpiration.\u003C/li\u003E\n\u003Cli\u003ERevocation.\u003C/li\u003E\n\u003Cli\u003EAccount security changes.\u003C/li\u003E\n\u003Cli\u003EInvalid refresh credentials.\u003C/li\u003E\n\u003Cli\u003EServer-side continuation restrictions.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe client must remain prepared to handle \u003Ccode\u003EReauthRequired\u003C/code\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022validate-current-authentication\u0022\u003E11. Validate Current Authentication\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003EValidateAsync\u003C/code\u003E to ask the server to validate the current authentication state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.ValidateAsync();\n\nif (result.IsValid)\n{\n // Current authentication is valid.\n}\nelse\n{\n // Authentication is not currently valid.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method returns \u003Ccode\u003EAuthValidationResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EIts properties include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EState\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECurrent session state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsValid\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether the state is \u003Ccode\u003EActive\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESnapshot\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional authentication state snapshot\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EChainId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional associated session chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERootId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional session root\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBoundDeviceId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional bound device identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022inspect-session-context\u0022\u003EInspect Session Context\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.ValidateAsync();\n\nif (result.IsValid \u0026amp;\u0026amp; result.ChainId is { } chainId)\n{\n // Use chainId for supported session-management operations.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENot every authentication mode necessarily provides all session hierarchy fields.\u003C/p\u003E\n\u003Cp\u003ETreat optional values as optional.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validateasync-versus-ui-authentication-state\u0022\u003EValidateAsync Versus UI Authentication State\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EValidateAsync\u003C/code\u003E performs an explicit server validation operation.\u003C/p\u003E\n\u003Cp\u003EIt should not be called on every UI render merely to determine whether a component should display authenticated content.\u003C/p\u003E\n\u003Cp\u003EFor UI authentication state, use the supported UltimateAuth state management integration, including \u003Ccode\u003EIUAuthStateManager\u003C/code\u003E where appropriate.\u003C/p\u003E\n\u003Cp\u003EExplicit validation is useful when an application needs to check current server-recognized authentication state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout\u0022\u003E12. Logout\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ELogoutAsync\u003C/code\u003E performs the current logout flow.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.LogoutAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method submits logout to the configured endpoint and observes the server response before clearing the local access token and publishing the logout event.\u003C/p\u003E\n\u003Cp\u003EAutomatic navigation can be disabled without disabling server-side logout.\u003C/p\u003E\n\u003Cp\u003EA failed logout response does not represent a successfully terminated authentication context.\u003C/p\u003E\n\u003Cp\u003EDepending on the application profile and configuration, logout may involve navigation and authentication state changes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-button\u0022\u003ELogout Button\u003C/h3\u003E\n\u003Cp\u003EA simple Blazor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\n\u0026lt;button @onclick=\u0026quot;LogoutAsync\u0026quot;\u0026gt;Logout\u0026lt;/button\u0026gt;\n\n@code {\n private async Task LogoutAsync()\n {\n await UAuthClient.Flows.LogoutAsync();\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ELogout is distinct from clearing local UI state.\u003C/p\u003E\n\u003Cp\u003ERemoving a local authentication indicator does not necessarily revoke authoritative server-managed authentication state.\u003C/p\u003E\n\u003Cp\u003EUse the supported logout flow to terminate authentication.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-a-specific-device\u0022\u003E13. Logout a Specific Device\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports revoking the session chain associated with a particular device context.\u003C/p\u003E\n\u003Cp\u003EThe relevant method is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003ELogoutMyDeviceAsync(LogoutDeviceRequest request)\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ELogoutDeviceRequest\u003C/code\u003E requires a \u003Ccode\u003ESessionChainId\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LogoutDeviceRequest\n{\n ChainId = chainId\n};\n\nvar result = await UAuthClient.Flows.LogoutMyDeviceAsync(request);\n\nif (result.IsSuccess)\n{\n // The requested device logout operation succeeded.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis operation targets a session chain, not an arbitrary individual session ID.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022current-device-behavior\u0022\u003ECurrent Device Behavior\u003C/h3\u003E\n\u003Cp\u003EThe returned \u003Ccode\u003ERevokeResult\u003C/code\u003E can indicate whether the affected chain is the current chain.\u003C/p\u003E\n\u003Cp\u003EWhen the operation succeeds and \u003Ccode\u003ECurrentChain\u003C/code\u003E is true, the client publishes a logout-related state event.\u003C/p\u003E\n\u003Cp\u003EThis allows the application to react when the currently authenticated device context has been revoked.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-other-devices\u0022\u003E14. Logout Other Devices\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003ELogoutMyOtherDevicesAsync\u003C/code\u003E to revoke other device-associated sessions while retaining the current one.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutMyOtherDevicesAsync();\n\nif (result.IsSuccess)\n{\n // Other devices were logged out.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is useful for account security pages that provide a \u003Cstrong\u003ELog out other devices\u003C/strong\u003E action.\u003C/p\u003E\n\u003Cp\u003EThe current authentication context is intended to remain active.\u003C/p\u003E\n\u003Cp\u003EThe server remains responsible for identifying the current session or chain and enforcing the appropriate revocation scope.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-all-devices\u0022\u003E15. Logout All Devices\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003ELogoutAllMyDevicesAsync\u003C/code\u003E to revoke all applicable sessions for the current user.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutAllMyDevicesAsync();\n\nif (result.IsSuccess)\n{\n // All applicable device sessions were revoked.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOn success, the client publishes a logout-related state event.\u003C/p\u003E\n\u003Cp\u003EThis operation is useful when a user suspects account compromise or wants to terminate existing authentication sessions across devices.\u003C/p\u003E\n\u003Cp\u003EIn JWT-based modes, previously issued access tokens may remain cryptographically valid until expiration unless additional revocation enforcement is configured.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022administrative-device-logout\u0022\u003E16. Administrative Device Logout\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth also exposes administrative session revocation operations.\u003C/p\u003E\n\u003Cp\u003EThese methods act on a specified user and require appropriate server-side authorization.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-one-user-device\u0022\u003ELogout One User Device\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutUserDeviceAsync(\n userKey,\n new LogoutDeviceRequest\n {\n ChainId = chainId\n });\n\nif (!result.IsSuccess)\n{\n // Handle the failure.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-other-devices-for-a-user\u0022\u003ELogout Other Devices for a User\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutUserOtherDevicesAsync(userKey, request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EHere, \u003Ccode\u003Erequest\u003C/code\u003E is a \u003Ccode\u003ELogoutOtherDevicesRequest\u003C/code\u003E identifying the chain to retain.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-all-devices-for-a-user\u0022\u003ELogout All Devices for a User\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutAllUserDevicesAsync(userKey);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAdministrative methods do not grant administrative privileges by themselves.\u003C/p\u003E\n\u003Cp\u003EThe server must authorize the actor and validate the target user and requested revocation scope.\u003C/p\u003E\n\u003Cp\u003EThese operations are particularly relevant to administration panels and account security workflows.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022building-login-forms-with-uauthloginform\u0022\u003E17. Building Login Forms with UAuthLoginForm\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth provides \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E, a reusable Blazor component that handles authentication form submission without requiring developers to implement the underlying flow orchestration themselves.\u003C/p\u003E\n\u003Cp\u003EThe component supports password-based login, PKCE completion through UAuthHub, configurable submission modes, structured validation feedback, and customizable UI content.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EYou design the login interface. UltimateAuth handles the authentication submission workflow.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022basic-usage\u0022\u003EBasic Usage\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E provides a complete, ready-to-use login form out of the box. No additional markup or credential bindings are required.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm /\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThat\u0027s it. UltimateAuth automatically renders the identifier field, password field, and submit button, and handles the authentication submission workflow.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECustomizing the Form\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EWhen you need a custom layout or styling, simply provide your own form content:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client.Blazor\n\n\u0026lt;UAuthLoginForm\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; autocomplete=\u0026quot;username\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; placeholder=\u0026quot;Password\u0026quot; autocomplete=\u0026quot;current-password\u0026quot; /\u0026gt;\n \u0026lt;button type=\u0026quot;submit\u0026quot;\u0026gt;Sign in\u0026lt;/button\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth handles the authentication workflow in both cases. Your custom fields only need the correct HTML \u003Ccode\u003Ename\u003C/code\u003E attributes; there is no need to bind credentials to Blazor component state.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022native-credential-submission\u0022\u003ENative Credential Submission\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E reads credentials directly from native browser form fields. It does not accept \u003Ccode\u003EIdentifier\u003C/code\u003E or \u003Ccode\u003ESecret\u003C/code\u003E component parameters.\u003C/p\u003E\n\u003Cp\u003EWhen providing custom \u003Ccode\u003EChildContent\u003C/code\u003E, the form must contain enabled input elements with the exact names \u003Ccode\u003EIdentifier\u003C/code\u003E and \u003Ccode\u003ESecret\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003ECredential values should not be bound to Blazor component state solely for submission. This is particularly important in Blazor Server, where interactive component bindings can transmit credential values over the SignalR connection.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant: Do Not Disable Credential Fields During Submission\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EHTML inputs marked as \u003Ccode\u003Edisabled\u003C/code\u003E are excluded from \u003Ccode\u003EFormData\u003C/code\u003E and native form submissions.\u003C/p\u003E\n\u003Cp\u003EDo not set \u003Ccode\u003EDisabled=\u0026quot;@isSubmitting\u0026quot;\u003C/code\u003E on the username or password fields. A login preview may succeed, but the subsequent native commit can fail because the credential fields are missing from the submitted form.\u003C/p\u003E\n\u003Cp\u003EInstead, disable the submit button while leaving the credential inputs enabled.\u003C/p\u003E\n\u003Cp\u003EIf you need to prevent editing during submission, consider \u003Ccode\u003Ereadonly\u003C/code\u003E where supported, while accounting for component behavior, browser autofill, and accessibility.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECustom Form Requirements\u003C/strong\u003E\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EUse \u003Ccode\u003Ename=\u0026quot;Identifier\u0026quot;\u003C/code\u003E and \u003Ccode\u003Ename=\u0026quot;Secret\u0026quot;\u003C/code\u003E exactly.\u003C/li\u003E\n\u003Cli\u003EKeep both credential inputs enabled throughout submission.\u003C/li\u003E\n\u003Cli\u003EAvoid duplicate inputs with these names.\u003C/li\u003E\n\u003Cli\u003EUse \u003Ccode\u003Etype=\u0026quot;password\u0026quot;\u003C/code\u003E and \u003Ccode\u003Eautocomplete=\u0026quot;current-password\u0026quot;\u003C/code\u003E for password fields.\u003C/li\u003E\n\u003Cli\u003EKeep custom submit controls inside \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EUse \u003Ccode\u003EOnSubmittingChanged\u003C/code\u003E to manage loading indicators and submit-button state.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E handles the try and commit orchestration. The native commit includes the browser form fields, device information, and antiforgery data required by the configured authentication flow.\u003C/p\u003E\n\u003Cp\u003EThe component automatically uses \u003Ccode\u003ETryAndCommit\u003C/code\u003E as its default submission mode.\u003C/p\u003E\n\u003Cp\u003EWhen submitted, it:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates that the identifier and secret are present.\u003C/li\u003E\n\u003Cli\u003ECreates the appropriate authentication request.\u003C/li\u003E\n\u003Cli\u003ECalls the UltimateAuth client flow.\u003C/li\u003E\n\u003Cli\u003EPerforms the configured try/commit behavior.\u003C/li\u003E\n\u003Cli\u003EExposes structured results through \u003Ccode\u003EOnTryResult\u003C/code\u003E.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe example assumes that UltimateAuth\u0027s Blazor services have already been registered and that the hosting environment permits the selected login flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022customizing-the-login-ui\u0022\u003ECustomizing the Login UI\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E uses \u003Ccode\u003EChildContent\u003C/code\u003E, allowing developers to use standard HTML elements or their preferred Blazor component library.\u003C/p\u003E\n\u003Cp\u003EFor example, with MudBlazor:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client.Blazor\n@using CodeBeam.UltimateAuth.Client\n\n\u0026lt;UAuthLoginForm SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot; OnTryResult=\u0026quot;HandleLoginResult\u0026quot; OnSubmittingChanged=\u0026quot;HandleSubmittingChanged\u0026quot;\u0026gt;\n \u0026lt;MudStack Spacing=\u0026quot;3\u0026quot;\u0026gt;\n \u0026lt;MudText Typo=\u0026quot;Typo.h5\u0026quot;\u0026gt;Sign in\u0026lt;/MudText\u0026gt;\n \u0026lt;MudTextField name=\u0026quot;Identifier\u0026quot; Label=\u0026quot;Email\u0026quot; Variant=\u0026quot;Variant.Outlined\u0026quot; /\u0026gt;\n \u0026lt;MudTextField name=\u0026quot;Secret\u0026quot; Label=\u0026quot;Password\u0026quot; InputType=\u0026quot;InputType.Password\u0026quot; Variant=\u0026quot;Variant.Outlined\u0026quot; /\u0026gt;\n\n \u0026lt;MudButton ButtonType=\u0026quot;ButtonType.Submit\u0026quot; Disabled=\u0026quot;@_isSubmitting\u0026quot; Variant=\u0026quot;Variant.Filled\u0026quot; Color=\u0026quot;Color.Primary\u0026quot; FullWidth\u0026gt;Sign in\u0026lt;/MudButton\u0026gt;\n\n @if (!string.IsNullOrWhiteSpace(error))\n {\n \u0026lt;MudAlert Severity=\u0026quot;Severity.Error\u0026quot;\u0026gt;@error\u0026lt;/MudAlert\u0026gt;\n }\n \u0026lt;/MudStack\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n@code {\n private bool _isSubmitting;\n private string? error;\n\n private Task HandleSubmittingChanged(bool submitting)\n {\n _isSubmitting = submitting;\n return Task.CompletedTask;\n }\n\n private Task HandleLoginResult(IUAuthTryResult result)\n {\n error = result.IsSuccess ? null : \u0026quot;Unable to sign in.\u0026quot;;\n return Task.CompletedTask;\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe form controls remain under your control.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth does not require a particular visual design, CSS framework, or component library.\u003C/p\u003E\n\u003Cp\u003EBecause the component renders an HTML form internally, place the submit button inside its child content and avoid nesting another HTML form within it.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submission-modes\u0022\u003ESubmission Modes\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ESubmitMode\u003C/code\u003E to control how the authentication attempt is executed.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EValidates the authentication attempt without committing login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAttempts authentication and commits on success\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits directly to the commit flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E is the default.\u003C/p\u003E\n\u003Cp\u003EFor interactive login forms that need validation feedback, it is generally the recommended choice.\u003C/p\u003E\n\u003Cp\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E does not invoke \u003Ccode\u003EOnTryResult\u003C/code\u003E, because it does not perform the structured try operation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-authentication-results\u0022\u003EHandling Authentication Results\u003C/h3\u003E\n\u003Cp\u003EThe component exposes an \u003Ccode\u003EOnTryResult\u003C/code\u003E callback:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm OnTryResult=\u0026quot;HandleResult\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback receives \u003Ccode\u003EIUAuthTryResult\u003C/code\u003E, allowing the same component to report password login and PKCE completion results.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eprivate Task HandleResult(IUAuthTryResult result)\n{\n if (!result.IsSuccess)\n {\n errorMessage = \u0026quot;Authentication failed.\u0026quot;;\n }\n\n return Task.CompletedTask;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor flow-specific details, inspect the concrete result type:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eprivate Task HandleResult(IUAuthTryResult result)\n{\n if (result is TryLoginResult loginResult)\n {\n if (loginResult.LockoutUntilUtc is not null)\n {\n errorMessage = \u0026quot;Your account is temporarily locked.\u0026quot;;\n }\n else if (loginResult.RequiresMfa)\n {\n // Continue the supported additional authentication workflow.\n }\n else if (!loginResult.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n }\n else if (result is TryPkceLoginResult pkceResult)\n {\n if (pkceResult.RetryWithNewPkce)\n {\n errorMessage = \u0026quot;Please restart the authentication flow.\u0026quot;;\n }\n else if (!pkceResult.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to complete authentication.\u0026quot;;\n }\n }\n\n return Task.CompletedTask;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback reports the structured try result. It does not replace authentication state management or server-side validation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-uauthloginform-with-pkce\u0022\u003EUsing UAuthLoginForm with PKCE\u003C/h3\u003E\n\u003Cp\u003EThe same component also supports PKCE login completion when hosted within a supported UAuthHub environment.\u003C/p\u003E\n\u003Cp\u003ESet \u003Ccode\u003ELoginType\u003C/code\u003E to \u003Ccode\u003EPkce\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm LoginType=\u0026quot;UAuthLoginType.Pkce\u0026quot; SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot; OnTryResult=\u0026quot;HandleLoginResult\u0026quot;\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; placeholder=\u0026quot;Password\u0026quot; /\u0026gt;\n \u0026lt;button type=\u0026quot;submit\u0026quot;\u0026gt;Continue\u0026lt;/button\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn PKCE mode, the component:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EResolves the relevant UAuthHub session context.\u003C/li\u003E\n\u003Cli\u003ERetrieves the authorization code and code verifier through the configured Hub services.\u003C/li\u003E\n\u003Cli\u003EBuilds a \u003Ccode\u003EPkceCompleteRequest\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EInvokes the corresponding PKCE completion flow.\u003C/li\u003E\n\u003Cli\u003EReports the structured result when a try-enabled submission mode is used.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe application does not need to manually construct the PKCE completion request for this form.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant:\u003C/strong\u003E PKCE mode requires a supported server-side UAuthHub environment. \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E checks the available Hub capabilities and throws when PKCE login is requested in an unsupported application profile.\u003C/p\u003E\n\u003Cp\u003EA Blazor WebAssembly application should initiate PKCE using \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E; the Hub-hosted login form handles the completion stage.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022return-url-handling\u0022\u003EReturn URL Handling\u003C/h3\u003E\n\u003Cp\u003EYou can provide an explicit return URL:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm ReturnUrl=\u0026quot;/dashboard\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe component resolves the effective return URL using the following precedence:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EExplicit \u003Ccode\u003EReturnUrl\u003C/code\u003E parameter.\u003C/li\u003E\n\u003Cli\u003EUAuthHub flow return URL when using PKCE.\u003C/li\u003E\n\u003Cli\u003ECurrent navigation URL.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThis allows a shared login component to participate in different authentication journeys without hardcoding navigation logic into the form.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022custom-login-endpoints\u0022\u003ECustom Login Endpoints\u003C/h3\u003E\n\u003Cp\u003EFor advanced integrations, the \u003Ccode\u003EEndpoint\u003C/code\u003E parameter allows the form\u0027s HTML action endpoint to be overridden:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm Endpoint=\u0026quot;/custom-login\u0026quot; SubmitMode=\u0026quot;UAuthSubmitMode.DirectCommit\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe endpoint is resolved relative to the configured UltimateAuth endpoint base path and multi-tenant settings.\u003C/p\u003E\n\u003Cp\u003ENote that \u003Ccode\u003EEndpoint\u003C/code\u003E affects the form\u0027s HTML action. Try-based submissions invoke the configured \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E endpoints, so changing \u003Ccode\u003EEndpoint\u003C/code\u003E alone does not redirect those SDK requests to a custom endpoint.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submit-the-form-programmatically\u0022\u003ESubmit the Form Programmatically\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E exposes \u003Ccode\u003ESubmitAsync\u003C/code\u003E, allowing submission through a component reference.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm @ref=\u0026quot;loginForm\u0026quot; AllowEnterKeyToSubmit=\u0026quot;false\u0026quot;\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; /\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n\u0026lt;button type=\u0026quot;button\u0026quot; @onclick=\u0026quot;SubmitLoginAsync\u0026quot;\u0026gt;\n Sign in\n\u0026lt;/button\u0026gt;\n\n@code {\n private UAuthLoginForm? loginForm;\n\n private async Task SubmitLoginAsync()\n {\n if (loginForm is not null)\n {\n await loginForm.SubmitAsync();\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ESubmitAsync\u003C/code\u003E must be called after the component has rendered.\u003C/p\u003E\n\u003Cp\u003EThis is useful when submission is initiated from a custom button, dialog, or application-specific interaction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022controlling-enter-key-submission\u0022\u003EControlling Enter-Key Submission\u003C/h3\u003E\n\u003Cp\u003EBy default, the component supports Enter-key submission.\u003C/p\u003E\n\u003Cp\u003EYou can disable its built-in hidden submit button:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm AllowEnterKeyToSubmit=\u0026quot;false\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis option controls the component\u0027s built-in Enter-key submit mechanism. Other submit buttons inside the form may still trigger normal browser form submission behavior.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reloading-pkce-context\u0022\u003EReloading PKCE Context\u003C/h3\u003E\n\u003Cp\u003EThe component exposes \u003Ccode\u003EReloadAsync\u003C/code\u003E to reload its Hub credentials and flow state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm @ref=\u0026quot;loginForm\u0026quot; LoginType=\u0026quot;UAuthLoginType.Pkce\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n@code {\n private UAuthLoginForm? loginForm;\n\n private async Task ReloadLoginContextAsync()\n {\n if (loginForm is not null)\n {\n await loginForm.ReloadAsync();\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is an advanced capability intended for scenarios where the associated Hub state changes and the component must refresh its internal context.\u003C/p\u003E\n\u003Cp\u003EIt does not initiate a new PKCE authorization flow by itself.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022component-parameters\u0022\u003EComponent Parameters\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EParameter\u003C/th\u003E\n\u003Cth\u003EType\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthLoginType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EPassword\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPassword or PKCE login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESubmitMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthSubmitMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmission strategy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERedirect destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoint\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECustom HTML form endpoint\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExplicit Hub session context\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAllowEnterKeyToSubmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Ebool\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBuilt-in Enter-key submit support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnTryResult\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EEventCallback\u0026lt;IUAuthTryResult\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003EStructured try result callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnSubmittingChanged\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EEventCallback\u0026lt;bool\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003ESubmission state change callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EChildContent\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ERenderFragment?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003ECustom form content\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-uauthloginform\u0022\u003EWhen to Use UAuthLoginForm\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E when building a Blazor login interface that should integrate directly with UltimateAuth\u0027s supported authentication flows.\u003C/p\u003E\n\u003Cp\u003EIt is particularly useful when:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EYou want to use your own component library without implementing the authentication submission logic.\u003C/li\u003E\n\u003Cli\u003EYou need structured login validation feedback.\u003C/li\u003E\n\u003Cli\u003EYou want to switch between try-only and commit behavior.\u003C/li\u003E\n\u003Cli\u003EYou are building a UAuthHub login page that completes PKCE.\u003C/li\u003E\n\u003Cli\u003EYou want to share login UI across supported Blazor hosting environments.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EFor application-specific workflows that cannot be expressed through the component, use \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E directly.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThe component handles the login workflow, while your application retains control over presentation, user experience, and surrounding application logic.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022common-integration-mistakes\u0022\u003E18. Common Integration Mistakes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022calling-direct-login-from-a-public-client\u0022\u003ECalling Direct Login from a Public Client\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E \u003Ccode\u003ELoginAsync\u003C/code\u003E throws because direct credential posting is disabled.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Use \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E and the supported PKCE completion flow. Do not enable \u003Ccode\u003EAllowCredentialPost\u003C/code\u003E to bypass the public-client restriction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022treating-tryonly-as-authentication\u0022\u003ETreating TryOnly as Authentication\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E The application receives \u003Ccode\u003EIsSuccess = true\u003C/code\u003E from \u003Ccode\u003ETryOnly\u003C/code\u003E and assumes the user is logged in.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E A successful try result does not commit authentication. Use \u003Ccode\u003ETryAndCommit\u003C/code\u003E or the appropriate commit flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-directcommit-skips-server-validation\u0022\u003EAssuming DirectCommit Skips Server Validation\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E DirectCommit is interpreted as a faster but less secure authentication mode.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E DirectCommit skips the separate client try stage. The server still validates the actual authentication request.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-every-refresh-rotates-tokens\u0022\u003EAssuming Every Refresh Rotates Tokens\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E The application requires \u003Ccode\u003ERefreshOutcome.Rotated\u003C/code\u003E for refresh success.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Check \u003Ccode\u003ERefreshResult.IsSuccess\u003C/code\u003E. Rotation, touch, and no-op behavior depend on the authentication mode and refresh strategy.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-a-session-id-for-device-logout\u0022\u003EUsing a Session ID for Device Logout\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E A session identifier is passed to a device logout operation.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E \u003Ccode\u003ELogoutMyDeviceAsync\u003C/code\u003E requires \u003Ccode\u003ELogoutDeviceRequest\u003C/code\u003E with a \u003Ccode\u003ESessionChainId\u003C/code\u003E.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-logout-immediately-invalidates-all-jwts\u0022\u003EAssuming Logout Immediately Invalidates All JWTs\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E An application expects every issued JWT access token to become unusable immediately after server-side logout.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Understand the enforcement behavior of SemiHybrid and PureJwt. Local JWT validation may continue accepting previously issued tokens until expiration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-validateasync-on-every-render\u0022\u003EUsing ValidateAsync on Every Render\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E Components repeatedly make validation requests just to display authenticated UI.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Use the appropriate authentication state integration for UI rendering, and reserve explicit validation for operations that require it.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/session-management\u0022\u003ESession Management\u003C/a\u003E \u2014 Inspect and manage session and device information.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/token-security\u0022\u003EToken Security\u003C/a\u003E \u2014 Understand token validity, refresh behavior, and revocation.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/refresh-rotation\u0022\u003ERefresh Rotation \u0026amp; Replay Protection\u003C/a\u003E \u2014 Explore refresh concurrency and reuse security.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E \u2014 Compare authentication behavior across modes.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E \u2014 Understand device-associated session chains.\u003C/li\u003E\n\u003C/ul\u003E\n", + "Html": "\n\u003Cp\u003EThe UltimateAuth Client SDK provides a high-level API for authentication workflows, including login, PKCE, session validation, refresh, logout, and device-specific session revocation.\u003C/p\u003E\n\u003Cp\u003EThese operations are exposed through \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E, which implements the \u003Ccode\u003EIFlowClient\u003C/code\u003E contract.\u003C/p\u003E\n\u003Cp\u003EThis guide shows how to use the authentication client in application code, handle structured results, configure interactive behavior, and choose the correct flow for different client environments.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022accessing-the-authentication-client\u0022\u003E1. Accessing the Authentication Client\u003C/h2\u003E\n\u003Cp\u003EIn a Blazor component, inject \u003Ccode\u003EIUAuthClient\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAuthentication operations are available through the \u003Ccode\u003EFlows\u003C/code\u003E property.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.RefreshAsync();\nawait UAuthClient.Flows.ValidateAsync();\nawait UAuthClient.Flows.LogoutAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe relevant methods are defined by \u003Ccode\u003EIFlowClient\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMethod\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmit a direct login flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAttempt login with configurable try/commit behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBeginPkceAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EStart a PKCE authentication flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECompletePkceLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EComplete a PKCE login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryCompletePkceLoginAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EComplete PKCE with structured try/commit behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh or continue authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidateAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EValidate current authentication state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELog out the current session\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutMyDeviceAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke a selected device-associated chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutMyOtherDevicesAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke other devices while retaining the current one\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogoutAllMyDevicesAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke all devices for the current user\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EAdministrative device logout operations are also available and covered later in this guide.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022choosing-the-correct-login-flow\u0022\u003E2. Choosing the Correct Login Flow\u003C/h2\u003E\n\u003Cp\u003EBefore implementing login, determine whether your application is a trusted server-hosted client or a public client.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient environment\u003C/th\u003E\n\u003Cth\u003ERecommended flow\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBlazor Server\u003C/td\u003E\n\u003Ctd\u003EDirect login or supported interactive login flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EUAuthHub\u003C/td\u003E\n\u003Ctd\u003EServer-hosted authentication flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBlazor WebAssembly\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBrowser SPA\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPublic native application\u003C/td\u003E\n\u003Ctd\u003EPKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EPublic clients must not rely on embedding a secret or trusting browser-executed code to protect credentials.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth restricts direct credential posting based on the configured application profile and login options.\u003C/p\u003E\n\u003Cp\u003EFor public clients, use the PKCE flow instead of enabling direct credential posting.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-login\u0022\u003E3. Direct Login\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E performs a direct login submission.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LoginRequest\n{\n Identifier = \u0026quot;user@example.com\u0026quot;,\n Secret = \u0026quot;password\u0026quot;\n};\n\nawait UAuthClient.Flows.LoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginAsync\u003C/code\u003E returns a structured login result describing the outcome of the submission.\u003C/p\u003E\n\u003Cp\u003EThe client discovers the effective login transport supported by the server.\u003C/p\u003E\n\u003Cp\u003EDepending on the authentication mode, credential delivery configuration, and return URL, login may use browser navigation or a fetch-based request.\u003C/p\u003E\n\u003Cp\u003EA navigation submission does not itself confirm successful server-side authentication. A fetch-based submission allows the client to observe the server response and process delivered credentials.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022login-transport-selection\u0022\u003ELogin Transport Selection\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth supports three login transport strategies:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ETransport\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically selects a compatible transport\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENavigation\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits the login through browser navigation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EFetch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits the login through an HTTP request and processes the response\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EAuto\u003C/code\u003E is the default and recommended strategy.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LoginAsync(\n request,\n returnUrl: \u0026quot;/dashboard\u0026quot;,\n transport: UAuthLoginTransport.Auto);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENavigation is suitable when the effective credential delivery configuration supports browser-managed authentication credentials.\u003C/p\u003E\n\u003Cp\u003EFetch is required when the client must observe a header-delivered access token.\u003C/p\u003E\n\u003Cp\u003EApplications can explicitly request fetch-based login:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LoginAsync(\n request,\n transport: UAuthLoginTransport.Fetch);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAn explicitly requested transport must be compatible with the effective server configuration.\u003C/p\u003E\n\u003Cp\u003EThe client does not silently downgrade an incompatible explicit navigation request.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022processing-header-delivered-access-tokens\u0022\u003EProcessing Header-Delivered Access Tokens\u003C/h3\u003E\n\u003Cp\u003EWhen login delivers an access token through a response header, UltimateAuth processes the token and stores it in the client-side token store.\u003C/p\u003E\n\u003Cp\u003EThe default token store is in-memory.\u003C/p\u003E\n\u003Cp\u003EApplications using the UltimateAuth client do not need to manually extract JWTs from login responses or construct authorization headers.\u003C/p\u003E\n\u003Cp\u003EThe client attaches the access token to supported authenticated requests and clears expired credentials from the token store.\u003C/p\u003E\n\u003Cp\u003EIn-memory storage does not persist access tokens across a full application reload.\u003C/p\u003E\n\u003Cp\u003EAuthentication continuation after a reload depends on the available refresh credential and the effective server configuration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022loginrequest-properties\u0022\u003ELoginRequest Properties\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ELoginRequest\u003C/code\u003E supports the following properties:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIdentifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESecret\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECredential secret\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECredentialType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECredential type; defaults to \u003Ccode\u003EPassword\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMetadata\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional request metadata\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERequestTokens\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EHint to request tokens when supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPreviewReceipt\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional receipt associated with a prior login preview\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EExample:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LoginRequest\n{\n Identifier = email,\n Secret = password,\n CredentialType = CredentialType.Password,\n RequestTokens = true\n};\n\nawait UAuthClient.Flows.LoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ERequestTokens\u003C/code\u003E is a hint, not a guarantee that tokens will be issued. The server\u0027s authentication mode and policy remain authoritative.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect-after-login\u0022\u003ERedirect After Login\u003C/h3\u003E\n\u003Cp\u003EProvide an explicit return URL when necessary:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.LoginAsync(request, returnUrl: \u0026quot;/dashboard\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe direct login flow resolves its return URL in the following order:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EThe explicit \u003Ccode\u003EreturnUrl\u003C/code\u003E argument.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E option.\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E option.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EFor example, client options can specify a default:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe return URL is part of the login workflow. It should not be treated as an authorization grant.\u003C/p\u003E\n\u003Cp\u003EApplications and servers must still enforce their redirect validation rules.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-login-with-tryloginasync\u0022\u003E4. Interactive Login with TryLoginAsync\u003C/h2\u003E\n\u003Cp\u003EFor interactive forms, \u003Ccode\u003ETryLoginAsync\u003C/code\u003E provides structured feedback before or during the authentication commit process.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryAndCommit);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is generally the more useful API for a login form that needs to display validation feedback.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submit-modes\u0022\u003ESubmit Modes\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthSubmitMode\u003C/code\u003E defines three submission behaviors.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExecute the try operation and return its result without committing authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmit directly to the commit endpoint without a separate try operation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETry first, then commit when the try operation succeeds\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese modes control client workflow, not whether the server validates authentication.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EDirectCommit does not bypass credential verification or server security requirements.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022tryonly-validate-without-login\u0022\u003ETryOnly: Validate Without Login\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ETryOnly\u003C/code\u003E when you want structured feedback without establishing an authenticated session.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryOnly);\n\nif (result.IsSuccess)\n{\n // The try operation succeeded.\n // Authentication has not been committed.\n}\nelse\n{\n // Display the appropriate feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis can be useful for a custom interactive workflow.\u003C/p\u003E\n\u003Cp\u003EA successful try result must not be interpreted as an authenticated application session.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022tryandcommit-interactive-login\u0022\u003ETryAndCommit: Interactive Login\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ETryAndCommit\u003C/code\u003E to combine structured validation with authentication commit.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.TryAndCommit,\n returnUrl: \u0026quot;/dashboard\u0026quot;);\n\nif (!result.IsSuccess)\n{\n // Show validation feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the try stage succeeds, the client proceeds to the commit operation through its configured transport.\u003C/p\u003E\n\u003Cp\u003EThis can involve navigation, so application code should not assume that execution always continues within the same component instance.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022directcommit-single-commit-submission\u0022\u003EDirectCommit: Single Commit Submission\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.TryLoginAsync(\n new LoginRequest\n {\n Identifier = email,\n Secret = password\n },\n UAuthSubmitMode.DirectCommit);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn this mode, the SDK submits the commit operation directly.\u003C/p\u003E\n\u003Cp\u003EThe method returns a \u003Ccode\u003ETryLoginResult\u003C/code\u003E with \u003Ccode\u003EIsSuccess = true\u003C/code\u003E after the navigation submission completes, but this is not a structured server-side authentication success confirmation.\u003C/p\u003E\n\u003Cp\u003EIf you need structured credential validation feedback, prefer \u003Ccode\u003ETryAndCommit\u003C/code\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-login-results\u0022\u003E5. Handling Login Results\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ETryLoginAsync\u003C/code\u003E returns \u003Ccode\u003ETryLoginResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EIts available properties include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsSuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether the try operation succeeded\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReason\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional authentication failure reason\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERemainingAttempts\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERemaining attempts, when provided\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELockoutUntilUtc\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELockout expiration, when provided\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERequiresMfa\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether additional authentication is required\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPreviewReceipt\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional receipt for subsequent flow handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EExample:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryLoginAsync(request, UAuthSubmitMode.TryOnly);\n\nif (!result.IsSuccess)\n{\n if (result.LockoutUntilUtc is not null)\n {\n errorMessage = $\u0026quot;Login temporarily unavailable until {result.LockoutUntilUtc:u}\u0026quot;;\n }\n else\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n\n return;\n}\n\nif (result.RequiresMfa)\n{\n // Continue with the supported additional authentication flow.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDo not expose sensitive internal authentication details unnecessarily.\u003C/p\u003E\n\u003Cp\u003EFor public-facing login forms, generic failure messages may be preferable to displaying every failure reason.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-transport-and-protocol-errors\u0022\u003EHandling Transport and Protocol Errors\u003C/h3\u003E\n\u003Cp\u003EA structured authentication failure is different from a network or protocol failure.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Etry\n{\n var result = await UAuthClient.Flows.TryLoginAsync(request, UAuthSubmitMode.TryAndCommit);\n\n if (!result.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n}\ncatch (UAuthTransportException)\n{\n errorMessage = \u0026quot;Authentication service is unavailable.\u0026quot;;\n}\ncatch (UAuthProtocolException)\n{\n errorMessage = \u0026quot;An authentication protocol error occurred.\u0026quot;;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUse the corresponding UltimateAuth client error namespace when referencing these exception types.\u003C/p\u003E\n\u003Cp\u003EA failed authentication attempt should normally be handled through the structured try result where supported. Transport and protocol exceptions indicate different failure categories.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022pkce-authentication\u0022\u003E6. PKCE Authentication\u003C/h2\u003E\n\u003Cp\u003EPKCE provides a proof mechanism for authorization-code-based authentication flows.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth supports PKCE using an S256 code challenge.\u003C/p\u003E\n\u003Cp\u003EThe SDK generates a cryptographically random verifier, derives its challenge, and coordinates the authorization flow.\u003C/p\u003E\n\u003Cp\u003EPublic clients such as Blazor WebAssembly should use PKCE rather than direct credential posting.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022start-pkce\u0022\u003EStart PKCE\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.BeginPkceAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EYou can provide a return URL:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.BeginPkceAsync(returnUrl: \u0026quot;/dashboard\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client performs the following operations:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EGenerates a PKCE code verifier.\u003C/li\u003E\n\u003Cli\u003EDerives an S256 code challenge.\u003C/li\u003E\n\u003Cli\u003ESends the authorization request.\u003C/li\u003E\n\u003Cli\u003EReceives an authorization code.\u003C/li\u003E\n\u003Cli\u003EInvokes the configured authorization callback, if any.\u003C/li\u003E\n\u003Cli\u003ENavigates to the configured UAuthHub login flow when automatic redirection is enabled.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe authorization code and verifier are used later to complete the flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-pkce\u0022\u003EConfigure PKCE\u003C/h3\u003E\n\u003Cp\u003EThe relevant client options include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.Enabled = true;\noptions.Pkce.AutoRedirect = true;\noptions.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EPKCE is enabled by default in \u003Ccode\u003EUAuthClientPkceLoginFlowOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EAutomatic redirection is also enabled by default.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022observe-authorization\u0022\u003EObserve Authorization\u003C/h3\u003E\n\u003Cp\u003EYou can register a callback that runs after the authorization code is received and before the automatic Hub redirect.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.OnAuthorized = async response =\u0026gt;\n{\n // Observe the authorization response.\n await Task.CompletedTask;\n};\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis callback is useful for application-specific coordination.\u003C/p\u003E\n\u003Cp\u003EDo not log authorization codes or expose them to unrelated components.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disable-automatic-redirection\u0022\u003EDisable Automatic Redirection\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AutoRedirect = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith this configuration, \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E still performs the authorization request and invokes \u003Ccode\u003EOnAuthorized\u003C/code\u003E, but it does not automatically navigate to the Hub login endpoint.\u003C/p\u003E\n\u003Cp\u003EThe application becomes responsible for coordinating the remaining flow.\u003C/p\u003E\n\u003Cp\u003EThis is an advanced integration option.\u003C/p\u003E\n\u003Cp\u003EA custom implementation must preserve the authorization code, verifier, and relevant context securely and complete the flow using the supported protocol.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-pkce-login\u0022\u003E7. Complete PKCE Login\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ECompletePkceLoginAsync\u003C/code\u003E submits the PKCE completion request.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new PkceCompleteRequest\n{\n AuthorizationCode = authorizationCode,\n CodeVerifier = codeVerifier,\n Identifier = email,\n Secret = password,\n ReturnUrl = \u0026quot;/dashboard\u0026quot;\n};\n\nawait UAuthClient.Flows.CompletePkceLoginAsync(request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe request model includes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuthorizationCode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECode obtained from the authorization step\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ECodeVerifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOriginal PKCE verifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIdentifier\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESecret\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin credential\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional post-login destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional Hub session context\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe authorization code and verifier must correspond to the same PKCE flow.\u003C/p\u003E\n\u003Cp\u003EDo not generate a new verifier when completing an existing authorization.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-pkce-completion\u0022\u003EInteractive PKCE Completion\u003C/h3\u003E\n\u003Cp\u003EFor structured feedback, use \u003Ccode\u003ETryCompletePkceLoginAsync\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryCompletePkceLoginAsync(\n request,\n UAuthSubmitMode.TryAndCommit);\n\nif (!result.IsSuccess)\n{\n // Display PKCE login feedback.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe same submit modes are supported:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022try-pkce-without-commit\u0022\u003ETry PKCE Without Commit\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.TryCompletePkceLoginAsync(request, UAuthSubmitMode.TryOnly);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis returns a \u003Ccode\u003ETryPkceLoginResult\u003C/code\u003E without committing a successful login.\u003C/p\u003E\n\u003Cp\u003EThe result includes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eresult.IsSuccess;\nresult.Reason;\nresult.RemainingAttempts;\nresult.LockoutUntilUtc;\nresult.RequiresMfa;\nresult.RetryWithNewPkce;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022retrywithnewpkce\u0022\u003ERetryWithNewPkce\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERetryWithNewPkce\u003C/code\u003E indicates that the client should begin a new PKCE authorization sequence rather than continuing with the existing authorization material.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eif (result.RetryWithNewPkce)\n{\n await UAuthClient.Flows.BeginPkceAsync(\u0026quot;/login\u0026quot;);\n return;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is useful when the current PKCE context can no longer be used.\u003C/p\u003E\n\u003Cp\u003EThe application should not repeatedly resubmit the same invalid authorization code and verifier.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022uauthhub-handoff-and-credential-ownership\u0022\u003EUAuthHub Handoff and Credential Ownership\u003C/h3\u003E\n\u003Cp\u003EA PKCE flow initiated by an application retains the initiating application\u0027s authentication context.\u003C/p\u003E\n\u003Cp\u003EWhen the user completes login through UAuthHub, the resulting credentials belong to the initiating application, not to the Hub\u0027s interactive login interface.\u003C/p\u003E\n\u003Cp\u003EThe Hub completes the authentication flow and returns the user to the validated application return URL.\u003C/p\u003E\n\u003Cp\u003EHeader-delivered access tokens associated with the initiating application must not be installed into the Hub\u0027s local authentication state.\u003C/p\u003E\n\u003Cp\u003EAfter returning to the initiating application, the client can restore authentication through the available session or refresh credentials.\u003C/p\u003E\n\u003Cp\u003EThis behavior preserves the original application and device context throughout the authentication journey.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-recovery\u0022\u003EAuthentication Recovery\u003C/h3\u003E\n\u003Cp\u003EThe client may recover a header-delivered access token when the application starts without a usable token but a compatible refresh credential remains available.\u003C/p\u003E\n\u003Cp\u003EThis allows authentication to continue after a full application reload or a supported UAuthHub handoff.\u003C/p\u003E\n\u003Cp\u003ERecovery does not bypass refresh-token validation, device binding, expiration, rotation, or server-side authentication policies.\u003C/p\u003E\n\u003Cp\u003ERecovery can fail when the refresh credential has expired, has been revoked, or is unavailable because of browser cookie restrictions.\u003C/p\u003E\n\u003Cp\u003ECross-site browser deployments must not assume that refresh cookies will always be available.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-credential-posting-restrictions\u0022\u003E8. Direct Credential Posting Restrictions\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth restricts direct credential posting according to the configured application profile.\u003C/p\u003E\n\u003Cp\u003EThe client option is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is the default.\u003C/p\u003E\n\u003Cp\u003EIf the current profile is not permitted to post credentials directly and the option has not enabled that capability, direct login methods throw an \u003Ccode\u003EInvalidOperationException\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor example, attempting direct login from a public client may produce an error indicating that PKCE is required.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022trusted-server-hosted-clients\u0022\u003ETrusted Server-Hosted Clients\u003C/h3\u003E\n\u003Cp\u003EThe option can be explicitly configured for a trusted server-hosted integration where direct credential posting is appropriate:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis must not be used to bypass PKCE requirements in a public browser application.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EDo not enable direct credential posting in production Blazor WebAssembly or SPA clients.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EAn application profile is an integration descriptor, not cryptographic proof that the caller is trusted.\u003C/p\u003E\n\u003Cp\u003EServer-side security requirements remain authoritative.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-authentication\u0022\u003E9. Refresh Authentication\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E requests continuation of the current authentication state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method returns \u003Ccode\u003ERefreshResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Epublic sealed record RefreshResult\n{\n public bool IsSuccess { get; init; }\n public int Status { get; init; }\n public RefreshOutcome Outcome { get; init; }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ERefresh behavior depends on the authentication mode.\u003C/p\u003E\n\u003Cp\u003EA refresh operation may update session activity, rotate authentication material, or determine that reauthentication is required.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-refresh-results\u0022\u003EHandling Refresh Results\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\nif (result.IsSuccess)\n{\n // Authentication continuation succeeded.\n}\nelse if (result.Outcome == RefreshOutcome.ReauthRequired)\n{\n // The current authentication can no longer continue.\n // Direct the user to the appropriate login flow.\n}\nelse\n{\n // Handle another unsuccessful refresh result.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EA \u003Ccode\u003E401 Unauthorized\u003C/code\u003E refresh response is handled as a normal reauthentication outcome.\u003C/p\u003E\n\u003Cp\u003EIt returns:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Enew RefreshResult\n{\n IsSuccess = false,\n Status = 401,\n Outcome = RefreshOutcome.ReauthRequired\n};\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENetwork and unexpected protocol failures can still produce exceptions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-outcomes\u0022\u003ERefresh Outcomes\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshOutcome\u003C/code\u003E defines the following values:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOutcome\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ENo specific semantic outcome\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGeneric successful refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENoOp\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ENo refresh state change was necessary\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETouched\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApplicable session activity was updated\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERotated\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERotation occurred\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthRequired\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication continuation is no longer permitted\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\nif (!result.IsSuccess)\n{\n return;\n}\n\nswitch (result.Outcome)\n{\n case RefreshOutcome.Rotated:\n // Authentication material was rotated.\n break;\n\n case RefreshOutcome.Touched:\n // Applicable session activity was updated.\n break;\n\n case RefreshOutcome.NoOp:\n // Successful refresh and no state change was required.\n break;\n\n case RefreshOutcome.Success:\n // Refresh succeeded without a more specific outcome.\n break;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022detailed-refresh-diagnostics\u0022\u003EDetailed Refresh Diagnostics\u003C/h3\u003E\n\u003Cp\u003EThe server may return a generic success outcome rather than exposing the internal refresh action.\u003C/p\u003E\n\u003Cp\u003EWhere supported, detailed refresh outcomes can be enabled through server diagnostics:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Diagnostics.EnableRefreshDetails = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis setting is intended for diagnostics and observability.\u003C/p\u003E\n\u003Cp\u003EApplications should not require a specific successful outcome such as \u003Ccode\u003ERotated\u003C/code\u003E or \u003Ccode\u003ETouched\u003C/code\u003E to consider refresh successful.\u003C/p\u003E\n\u003Cp\u003EUse \u003Ccode\u003EIsSuccess\u003C/code\u003E for the primary success decision.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-and-automatic-refresh\u0022\u003EManual and Automatic Refresh\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003ERefreshAsync\u003C/code\u003E has an optional \u003Ccode\u003EisAuto\u003C/code\u003E argument.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Manual refresh\nawait UAuthClient.Flows.RefreshAsync();\n\n// Refresh initiated by automatic coordination\nawait UAuthClient.Flows.RefreshAsync(isAuto: true);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe parameter distinguishes automatic refresh activity for client diagnostics.\u003C/p\u003E\n\u003Cp\u003EIt does not select a different authentication mode or override the server\u0027s refresh policy.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh\u0022\u003E10. Automatic Refresh\u003C/h2\u003E\n\u003Cp\u003EApplications do not need to manually refresh authentication before every protected request.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth enables proactive and reactive refresh by default.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Proactive = true;\n options.AutoRefresh.Reactive = true;\n options.AutoRefresh.Background = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EProactive refresh renews authentication before eligible authenticated requests.\u003C/p\u003E\n\u003Cp\u003EReactive refresh provides recovery from supported authentication challenges.\u003C/p\u003E\n\u003Cp\u003EBackground refresh can be enabled when independent authentication renewal is required.\u003C/p\u003E\n\u003Cp\u003EManual refresh remains available through \u003Ccode\u003EUAuthClient.Flows.RefreshAsync()\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor configuration, credential-aware scheduling, concurrency, session policy alignment, and diagnostics, see the dedicated \u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E guide.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022validate-current-authentication\u0022\u003E11. Validate Current Authentication\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003EValidateAsync\u003C/code\u003E to ask the server to validate the current authentication state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.ValidateAsync();\n\nif (result.IsValid)\n{\n // Current authentication is valid.\n}\nelse\n{\n // Authentication is not currently valid.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method returns \u003Ccode\u003EAuthValidationResult\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EIts properties include:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EState\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECurrent session state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsValid\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether the state is \u003Ccode\u003EActive\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESnapshot\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional authentication state snapshot\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EChainId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional associated session chain\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERootId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional session root\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBoundDeviceId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EOptional bound device identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022inspect-session-context\u0022\u003EInspect Session Context\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.ValidateAsync();\n\nif (result.IsValid \u0026amp;\u0026amp; result.ChainId is { } chainId)\n{\n // Use chainId for supported session-management operations.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENot every authentication mode necessarily provides all session hierarchy fields.\u003C/p\u003E\n\u003Cp\u003ETreat optional values as optional.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validateasync-versus-ui-authentication-state\u0022\u003EValidateAsync Versus UI Authentication State\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EValidateAsync\u003C/code\u003E performs an explicit server validation operation.\u003C/p\u003E\n\u003Cp\u003EIt should not be called on every UI render merely to determine whether a component should display authenticated content.\u003C/p\u003E\n\u003Cp\u003EFor UI authentication state, use the supported UltimateAuth state management integration, including \u003Ccode\u003EIUAuthStateManager\u003C/code\u003E where appropriate.\u003C/p\u003E\n\u003Cp\u003EExplicit validation is useful when an application needs to check current server-recognized authentication state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout\u0022\u003E12. Logout\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ELogoutAsync\u003C/code\u003E performs the current logout flow.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Flows.LogoutAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe method submits logout to the configured endpoint and observes the server response before clearing the local access token and publishing the logout event.\u003C/p\u003E\n\u003Cp\u003EAutomatic navigation can be disabled without disabling server-side logout.\u003C/p\u003E\n\u003Cp\u003EA failed logout response does not represent a successfully terminated authentication context.\u003C/p\u003E\n\u003Cp\u003EDepending on the application profile and configuration, logout may involve navigation and authentication state changes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-button\u0022\u003ELogout Button\u003C/h3\u003E\n\u003Cp\u003EA simple Blazor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\n\u0026lt;button @onclick=\u0026quot;LogoutAsync\u0026quot;\u0026gt;Logout\u0026lt;/button\u0026gt;\n\n@code {\n private async Task LogoutAsync()\n {\n await UAuthClient.Flows.LogoutAsync();\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ELogout is distinct from clearing local UI state.\u003C/p\u003E\n\u003Cp\u003ERemoving a local authentication indicator does not necessarily revoke authoritative server-managed authentication state.\u003C/p\u003E\n\u003Cp\u003EUse the supported logout flow to terminate authentication.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-a-specific-device\u0022\u003E13. Logout a Specific Device\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports revoking the session chain associated with a particular device context.\u003C/p\u003E\n\u003Cp\u003EThe relevant method is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003ELogoutMyDeviceAsync(LogoutDeviceRequest request)\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ELogoutDeviceRequest\u003C/code\u003E requires a \u003Ccode\u003ESessionChainId\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar request = new LogoutDeviceRequest\n{\n ChainId = chainId\n};\n\nvar result = await UAuthClient.Flows.LogoutMyDeviceAsync(request);\n\nif (result.IsSuccess)\n{\n // The requested device logout operation succeeded.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis operation targets a session chain, not an arbitrary individual session ID.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022current-device-behavior\u0022\u003ECurrent Device Behavior\u003C/h3\u003E\n\u003Cp\u003EThe returned \u003Ccode\u003ERevokeResult\u003C/code\u003E can indicate whether the affected chain is the current chain.\u003C/p\u003E\n\u003Cp\u003EWhen the operation succeeds and \u003Ccode\u003ECurrentChain\u003C/code\u003E is true, the client publishes a logout-related state event.\u003C/p\u003E\n\u003Cp\u003EThis allows the application to react when the currently authenticated device context has been revoked.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-other-devices\u0022\u003E14. Logout Other Devices\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003ELogoutMyOtherDevicesAsync\u003C/code\u003E to revoke other device-associated sessions while retaining the current one.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutMyOtherDevicesAsync();\n\nif (result.IsSuccess)\n{\n // Other devices were logged out.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is useful for account security pages that provide a \u003Cstrong\u003ELog out other devices\u003C/strong\u003E action.\u003C/p\u003E\n\u003Cp\u003EThe current authentication context is intended to remain active.\u003C/p\u003E\n\u003Cp\u003EThe server remains responsible for identifying the current session or chain and enforcing the appropriate revocation scope.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-all-devices\u0022\u003E15. Logout All Devices\u003C/h2\u003E\n\u003Cp\u003EUse \u003Ccode\u003ELogoutAllMyDevicesAsync\u003C/code\u003E to revoke all applicable sessions for the current user.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutAllMyDevicesAsync();\n\nif (result.IsSuccess)\n{\n // All applicable device sessions were revoked.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOn success, the client publishes a logout-related state event.\u003C/p\u003E\n\u003Cp\u003EThis operation is useful when a user suspects account compromise or wants to terminate existing authentication sessions across devices.\u003C/p\u003E\n\u003Cp\u003EIn JWT-based modes, previously issued access tokens may remain cryptographically valid until expiration unless additional revocation enforcement is configured.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022administrative-device-logout\u0022\u003E16. Administrative Device Logout\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth also exposes administrative session revocation operations.\u003C/p\u003E\n\u003Cp\u003EThese methods act on a specified user and require appropriate server-side authorization.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-one-user-device\u0022\u003ELogout One User Device\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutUserDeviceAsync(\n userKey,\n new LogoutDeviceRequest\n {\n ChainId = chainId\n });\n\nif (!result.IsSuccess)\n{\n // Handle the failure.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-other-devices-for-a-user\u0022\u003ELogout Other Devices for a User\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutUserOtherDevicesAsync(userKey, request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EHere, \u003Ccode\u003Erequest\u003C/code\u003E is a \u003Ccode\u003ELogoutOtherDevicesRequest\u003C/code\u003E identifying the chain to retain.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022logout-all-devices-for-a-user\u0022\u003ELogout All Devices for a User\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.LogoutAllUserDevicesAsync(userKey);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAdministrative methods do not grant administrative privileges by themselves.\u003C/p\u003E\n\u003Cp\u003EThe server must authorize the actor and validate the target user and requested revocation scope.\u003C/p\u003E\n\u003Cp\u003EThese operations are particularly relevant to administration panels and account security workflows.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022building-login-forms-with-uauthloginform\u0022\u003E17. Building Login Forms with UAuthLoginForm\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth provides \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E, a reusable Blazor component that handles authentication form submission without requiring developers to implement the underlying flow orchestration themselves.\u003C/p\u003E\n\u003Cp\u003EThe component supports password-based login, PKCE completion through UAuthHub, configurable submission modes, structured validation feedback, and customizable UI content.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EYou design the login interface. UltimateAuth handles the authentication submission workflow.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022basic-usage\u0022\u003EBasic Usage\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E provides a complete, ready-to-use login form out of the box. No additional markup or credential bindings are required.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm /\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThat\u0027s it. UltimateAuth automatically renders the identifier field, password field, and submit button, and handles the authentication submission workflow.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECustomizing the Form\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EWhen you need a custom layout or styling, simply provide your own form content:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client.Blazor\n\n\u0026lt;UAuthLoginForm\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; autocomplete=\u0026quot;username\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; placeholder=\u0026quot;Password\u0026quot; autocomplete=\u0026quot;current-password\u0026quot; /\u0026gt;\n \u0026lt;button type=\u0026quot;submit\u0026quot;\u0026gt;Sign in\u0026lt;/button\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth handles the authentication workflow in both cases. Your custom fields only need the correct HTML \u003Ccode\u003Ename\u003C/code\u003E attributes; there is no need to bind credentials to Blazor component state.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022native-credential-submission\u0022\u003ENative Credential Submission\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E reads credentials directly from native browser form fields. It does not accept \u003Ccode\u003EIdentifier\u003C/code\u003E or \u003Ccode\u003ESecret\u003C/code\u003E component parameters.\u003C/p\u003E\n\u003Cp\u003EWhen providing custom \u003Ccode\u003EChildContent\u003C/code\u003E, the form must contain enabled input elements with the exact names \u003Ccode\u003EIdentifier\u003C/code\u003E and \u003Ccode\u003ESecret\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003ECredential values should not be bound to Blazor component state solely for submission. This is particularly important in Blazor Server, where interactive component bindings can transmit credential values over the SignalR connection.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant: Do Not Disable Credential Fields During Submission\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EHTML inputs marked as \u003Ccode\u003Edisabled\u003C/code\u003E are excluded from \u003Ccode\u003EFormData\u003C/code\u003E and native form submissions.\u003C/p\u003E\n\u003Cp\u003EDo not set \u003Ccode\u003EDisabled=\u0026quot;@isSubmitting\u0026quot;\u003C/code\u003E on the username or password fields. A login preview may succeed, but the subsequent native commit can fail because the credential fields are missing from the submitted form.\u003C/p\u003E\n\u003Cp\u003EInstead, disable the submit button while leaving the credential inputs enabled.\u003C/p\u003E\n\u003Cp\u003EIf you need to prevent editing during submission, consider \u003Ccode\u003Ereadonly\u003C/code\u003E where supported, while accounting for component behavior, browser autofill, and accessibility.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECustom Form Requirements\u003C/strong\u003E\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EUse \u003Ccode\u003Ename=\u0026quot;Identifier\u0026quot;\u003C/code\u003E and \u003Ccode\u003Ename=\u0026quot;Secret\u0026quot;\u003C/code\u003E exactly.\u003C/li\u003E\n\u003Cli\u003EKeep both credential inputs enabled throughout submission.\u003C/li\u003E\n\u003Cli\u003EAvoid duplicate inputs with these names.\u003C/li\u003E\n\u003Cli\u003EUse \u003Ccode\u003Etype=\u0026quot;password\u0026quot;\u003C/code\u003E and \u003Ccode\u003Eautocomplete=\u0026quot;current-password\u0026quot;\u003C/code\u003E for password fields.\u003C/li\u003E\n\u003Cli\u003EKeep custom submit controls inside \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EUse \u003Ccode\u003EOnSubmittingChanged\u003C/code\u003E to manage loading indicators and submit-button state.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E handles the try and commit orchestration. The native commit includes the browser form fields, device information, and antiforgery data required by the configured authentication flow.\u003C/p\u003E\n\u003Cp\u003EThe component automatically uses \u003Ccode\u003ETryAndCommit\u003C/code\u003E as its default submission mode.\u003C/p\u003E\n\u003Cp\u003EWhen submitted, it:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EValidates that the identifier and secret are present.\u003C/li\u003E\n\u003Cli\u003ECreates the appropriate authentication request.\u003C/li\u003E\n\u003Cli\u003ECalls the UltimateAuth client flow.\u003C/li\u003E\n\u003Cli\u003EPerforms the configured try/commit behavior.\u003C/li\u003E\n\u003Cli\u003EExposes structured results through \u003Ccode\u003EOnTryResult\u003C/code\u003E.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe example assumes that UltimateAuth\u0027s Blazor services have already been registered and that the hosting environment permits the selected login flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022customizing-the-login-ui\u0022\u003ECustomizing the Login UI\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E uses \u003Ccode\u003EChildContent\u003C/code\u003E, allowing developers to use standard HTML elements or their preferred Blazor component library.\u003C/p\u003E\n\u003Cp\u003EFor example, with MudBlazor:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client.Blazor\n@using CodeBeam.UltimateAuth.Client\n\n\u0026lt;UAuthLoginForm SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot; OnTryResult=\u0026quot;HandleLoginResult\u0026quot; OnSubmittingChanged=\u0026quot;HandleSubmittingChanged\u0026quot;\u0026gt;\n \u0026lt;MudStack Spacing=\u0026quot;3\u0026quot;\u0026gt;\n \u0026lt;MudText Typo=\u0026quot;Typo.h5\u0026quot;\u0026gt;Sign in\u0026lt;/MudText\u0026gt;\n \u0026lt;MudTextField name=\u0026quot;Identifier\u0026quot; Label=\u0026quot;Email\u0026quot; Variant=\u0026quot;Variant.Outlined\u0026quot; /\u0026gt;\n \u0026lt;MudTextField name=\u0026quot;Secret\u0026quot; Label=\u0026quot;Password\u0026quot; InputType=\u0026quot;InputType.Password\u0026quot; Variant=\u0026quot;Variant.Outlined\u0026quot; /\u0026gt;\n\n \u0026lt;MudButton ButtonType=\u0026quot;ButtonType.Submit\u0026quot; Disabled=\u0026quot;@_isSubmitting\u0026quot; Variant=\u0026quot;Variant.Filled\u0026quot; Color=\u0026quot;Color.Primary\u0026quot; FullWidth\u0026gt;Sign in\u0026lt;/MudButton\u0026gt;\n\n @if (!string.IsNullOrWhiteSpace(error))\n {\n \u0026lt;MudAlert Severity=\u0026quot;Severity.Error\u0026quot;\u0026gt;@error\u0026lt;/MudAlert\u0026gt;\n }\n \u0026lt;/MudStack\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n@code {\n private bool _isSubmitting;\n private string? error;\n\n private Task HandleSubmittingChanged(bool submitting)\n {\n _isSubmitting = submitting;\n return Task.CompletedTask;\n }\n\n private Task HandleLoginResult(IUAuthTryResult result)\n {\n error = result.IsSuccess ? null : \u0026quot;Unable to sign in.\u0026quot;;\n return Task.CompletedTask;\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe form controls remain under your control.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth does not require a particular visual design, CSS framework, or component library.\u003C/p\u003E\n\u003Cp\u003EBecause the component renders an HTML form internally, place the submit button inside its child content and avoid nesting another HTML form within it.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submission-modes\u0022\u003ESubmission Modes\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003ESubmitMode\u003C/code\u003E to control how the authentication attempt is executed.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryOnly\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EValidates the authentication attempt without committing login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAttempts authentication and commits on success\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmits directly to the commit flow\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E is the default.\u003C/p\u003E\n\u003Cp\u003EFor interactive login forms that need validation feedback, it is generally the recommended choice.\u003C/p\u003E\n\u003Cp\u003E\u003Ccode\u003EDirectCommit\u003C/code\u003E does not invoke \u003Ccode\u003EOnTryResult\u003C/code\u003E, because it does not perform the structured try operation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-authentication-results\u0022\u003EHandling Authentication Results\u003C/h3\u003E\n\u003Cp\u003EThe component exposes an \u003Ccode\u003EOnTryResult\u003C/code\u003E callback:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm OnTryResult=\u0026quot;HandleResult\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback receives \u003Ccode\u003EIUAuthTryResult\u003C/code\u003E, allowing the same component to report password login and PKCE completion results.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eprivate Task HandleResult(IUAuthTryResult result)\n{\n if (!result.IsSuccess)\n {\n errorMessage = \u0026quot;Authentication failed.\u0026quot;;\n }\n\n return Task.CompletedTask;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor flow-specific details, inspect the concrete result type:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eprivate Task HandleResult(IUAuthTryResult result)\n{\n if (result is TryLoginResult loginResult)\n {\n if (loginResult.LockoutUntilUtc is not null)\n {\n errorMessage = \u0026quot;Your account is temporarily locked.\u0026quot;;\n }\n else if (loginResult.RequiresMfa)\n {\n // Continue the supported additional authentication workflow.\n }\n else if (!loginResult.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to sign in.\u0026quot;;\n }\n }\n else if (result is TryPkceLoginResult pkceResult)\n {\n if (pkceResult.RetryWithNewPkce)\n {\n errorMessage = \u0026quot;Please restart the authentication flow.\u0026quot;;\n }\n else if (!pkceResult.IsSuccess)\n {\n errorMessage = \u0026quot;Unable to complete authentication.\u0026quot;;\n }\n }\n\n return Task.CompletedTask;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback reports the structured try result. It does not replace authentication state management or server-side validation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-uauthloginform-with-pkce\u0022\u003EUsing UAuthLoginForm with PKCE\u003C/h3\u003E\n\u003Cp\u003EThe same component also supports PKCE login completion when hosted within a supported UAuthHub environment.\u003C/p\u003E\n\u003Cp\u003ESet \u003Ccode\u003ELoginType\u003C/code\u003E to \u003Ccode\u003EPkce\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm LoginType=\u0026quot;UAuthLoginType.Pkce\u0026quot; SubmitMode=\u0026quot;UAuthSubmitMode.TryAndCommit\u0026quot; OnTryResult=\u0026quot;HandleLoginResult\u0026quot;\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; placeholder=\u0026quot;Password\u0026quot; /\u0026gt;\n \u0026lt;button type=\u0026quot;submit\u0026quot;\u0026gt;Continue\u0026lt;/button\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIn PKCE mode, the component:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EResolves the relevant UAuthHub session context.\u003C/li\u003E\n\u003Cli\u003ERetrieves the authorization code and code verifier through the configured Hub services.\u003C/li\u003E\n\u003Cli\u003EBuilds a \u003Ccode\u003EPkceCompleteRequest\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EInvokes the corresponding PKCE completion flow.\u003C/li\u003E\n\u003Cli\u003EReports the structured result when a try-enabled submission mode is used.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe application does not need to manually construct the PKCE completion request for this form.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant:\u003C/strong\u003E PKCE mode requires a supported server-side UAuthHub environment. \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E checks the available Hub capabilities and throws when PKCE login is requested in an unsupported application profile.\u003C/p\u003E\n\u003Cp\u003EA Blazor WebAssembly application should initiate PKCE using \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E; the Hub-hosted login form handles the completion stage.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022return-url-handling\u0022\u003EReturn URL Handling\u003C/h3\u003E\n\u003Cp\u003EYou can provide an explicit return URL:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm ReturnUrl=\u0026quot;/dashboard\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe component resolves the effective return URL using the following precedence:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EExplicit \u003Ccode\u003EReturnUrl\u003C/code\u003E parameter.\u003C/li\u003E\n\u003Cli\u003EUAuthHub flow return URL when using PKCE.\u003C/li\u003E\n\u003Cli\u003ECurrent navigation URL.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThis allows a shared login component to participate in different authentication journeys without hardcoding navigation logic into the form.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022custom-login-endpoints\u0022\u003ECustom Login Endpoints\u003C/h3\u003E\n\u003Cp\u003EFor advanced integrations, the \u003Ccode\u003EEndpoint\u003C/code\u003E parameter allows the form\u0027s HTML action endpoint to be overridden:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm Endpoint=\u0026quot;/custom-login\u0026quot; SubmitMode=\u0026quot;UAuthSubmitMode.DirectCommit\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe endpoint is resolved relative to the configured UltimateAuth endpoint base path and multi-tenant settings.\u003C/p\u003E\n\u003Cp\u003ENote that \u003Ccode\u003EEndpoint\u003C/code\u003E affects the form\u0027s HTML action. Try-based submissions invoke the configured \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E endpoints, so changing \u003Ccode\u003EEndpoint\u003C/code\u003E alone does not redirect those SDK requests to a custom endpoint.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022submit-the-form-programmatically\u0022\u003ESubmit the Form Programmatically\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthLoginForm\u003C/code\u003E exposes \u003Ccode\u003ESubmitAsync\u003C/code\u003E, allowing submission through a component reference.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm @ref=\u0026quot;loginForm\u0026quot; AllowEnterKeyToSubmit=\u0026quot;false\u0026quot;\u0026gt;\n \u0026lt;input name=\u0026quot;Identifier\u0026quot; placeholder=\u0026quot;Email\u0026quot; /\u0026gt;\n \u0026lt;input name=\u0026quot;Secret\u0026quot; type=\u0026quot;password\u0026quot; /\u0026gt;\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n\u0026lt;button type=\u0026quot;button\u0026quot; @onclick=\u0026quot;SubmitLoginAsync\u0026quot;\u0026gt;\n Sign in\n\u0026lt;/button\u0026gt;\n\n@code {\n private UAuthLoginForm? loginForm;\n\n private async Task SubmitLoginAsync()\n {\n if (loginForm is not null)\n {\n await loginForm.SubmitAsync();\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ESubmitAsync\u003C/code\u003E must be called after the component has rendered.\u003C/p\u003E\n\u003Cp\u003EThis is useful when submission is initiated from a custom button, dialog, or application-specific interaction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022controlling-enter-key-submission\u0022\u003EControlling Enter-Key Submission\u003C/h3\u003E\n\u003Cp\u003EBy default, the component supports Enter-key submission.\u003C/p\u003E\n\u003Cp\u003EYou can disable its built-in hidden submit button:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm AllowEnterKeyToSubmit=\u0026quot;false\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis option controls the component\u0027s built-in Enter-key submit mechanism. Other submit buttons inside the form may still trigger normal browser form submission behavior.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reloading-pkce-context\u0022\u003EReloading PKCE Context\u003C/h3\u003E\n\u003Cp\u003EThe component exposes \u003Ccode\u003EReloadAsync\u003C/code\u003E to reload its Hub credentials and flow state.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E\u0026lt;UAuthLoginForm @ref=\u0026quot;loginForm\u0026quot; LoginType=\u0026quot;UAuthLoginType.Pkce\u0026quot;\u0026gt;\n ...\n\u0026lt;/UAuthLoginForm\u0026gt;\n\n@code {\n private UAuthLoginForm? loginForm;\n\n private async Task ReloadLoginContextAsync()\n {\n if (loginForm is not null)\n {\n await loginForm.ReloadAsync();\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is an advanced capability intended for scenarios where the associated Hub state changes and the component must refresh its internal context.\u003C/p\u003E\n\u003Cp\u003EIt does not initiate a new PKCE authorization flow by itself.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022component-parameters\u0022\u003EComponent Parameters\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EParameter\u003C/th\u003E\n\u003Cth\u003EType\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthLoginType\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EPassword\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPassword or PKCE login\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESubmitMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthSubmitMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryAndCommit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESubmission strategy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERedirect destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoint\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECustom HTML form endpoint\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubSessionId?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExplicit Hub session context\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAllowEnterKeyToSubmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Ebool\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBuilt-in Enter-key submit support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnTryResult\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EEventCallback\u0026lt;IUAuthTryResult\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003EStructured try result callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnSubmittingChanged\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EEventCallback\u0026lt;bool\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003ESubmission state change callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EChildContent\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ERenderFragment?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u2014\u003C/td\u003E\n\u003Ctd\u003ECustom form content\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-uauthloginform\u0022\u003EWhen to Use UAuthLoginForm\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003EUAuthLoginForm\u003C/code\u003E when building a Blazor login interface that should integrate directly with UltimateAuth\u0027s supported authentication flows.\u003C/p\u003E\n\u003Cp\u003EIt is particularly useful when:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EYou want to use your own component library without implementing the authentication submission logic.\u003C/li\u003E\n\u003Cli\u003EYou need structured login validation feedback.\u003C/li\u003E\n\u003Cli\u003EYou want to switch between try-only and commit behavior.\u003C/li\u003E\n\u003Cli\u003EYou are building a UAuthHub login page that completes PKCE.\u003C/li\u003E\n\u003Cli\u003EYou want to share login UI across supported Blazor hosting environments.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EFor application-specific workflows that cannot be expressed through the component, use \u003Ccode\u003EUAuthClient.Flows\u003C/code\u003E directly.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThe component handles the login workflow, while your application retains control over presentation, user experience, and surrounding application logic.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022common-integration-mistakes\u0022\u003E18. Common Integration Mistakes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022calling-direct-login-from-a-public-client\u0022\u003ECalling Direct Login from a Public Client\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E \u003Ccode\u003ELoginAsync\u003C/code\u003E throws because direct credential posting is disabled.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Use \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E and the supported PKCE completion flow. Do not enable \u003Ccode\u003EAllowCredentialPost\u003C/code\u003E to bypass the public-client restriction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022treating-tryonly-as-authentication\u0022\u003ETreating TryOnly as Authentication\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E The application receives \u003Ccode\u003EIsSuccess = true\u003C/code\u003E from \u003Ccode\u003ETryOnly\u003C/code\u003E and assumes the user is logged in.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E A successful try result does not commit authentication. Use \u003Ccode\u003ETryAndCommit\u003C/code\u003E or the appropriate commit flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-directcommit-skips-server-validation\u0022\u003EAssuming DirectCommit Skips Server Validation\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E DirectCommit is interpreted as a faster but less secure authentication mode.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E DirectCommit skips the separate client try stage. The server still validates the actual authentication request.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-every-refresh-rotates-tokens\u0022\u003EAssuming Every Refresh Rotates Tokens\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E The application requires \u003Ccode\u003ERefreshOutcome.Rotated\u003C/code\u003E for refresh success.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Check \u003Ccode\u003ERefreshResult.IsSuccess\u003C/code\u003E. Rotation, touch, and no-op behavior depend on the authentication mode and refresh strategy.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-a-session-id-for-device-logout\u0022\u003EUsing a Session ID for Device Logout\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E A session identifier is passed to a device logout operation.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E \u003Ccode\u003ELogoutMyDeviceAsync\u003C/code\u003E requires \u003Ccode\u003ELogoutDeviceRequest\u003C/code\u003E with a \u003Ccode\u003ESessionChainId\u003C/code\u003E.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-logout-immediately-invalidates-all-jwts\u0022\u003EAssuming Logout Immediately Invalidates All JWTs\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E An application expects every issued JWT access token to become unusable immediately after server-side logout.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Understand the enforcement behavior of SemiHybrid and PureJwt. Local JWT validation may continue accepting previously issued tokens until expiration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-validateasync-on-every-render\u0022\u003EUsing ValidateAsync on Every Render\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003EProblem:\u003C/strong\u003E Components repeatedly make validation requests just to display authenticated UI.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Use the appropriate authentication state integration for UI rendering, and reserve explicit validation for operations that require it.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/session-management\u0022\u003ESession Management\u003C/a\u003E \u2014 Inspect and manage session and device information.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/token-security\u0022\u003EToken Security\u003C/a\u003E \u2014 Understand token validity, refresh behavior, and revocation.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/refresh-rotation\u0022\u003ERefresh Rotation \u0026amp; Replay Protection\u003C/a\u003E \u2014 Explore refresh concurrency and reuse security.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E \u2014 Compare authentication behavior across modes.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E \u2014 Understand device-associated session chains.\u003C/li\u003E\n\u003C/ul\u003E\n", "Headings": [ { "Id": "accessing-the-authentication-client", @@ -164,15 +164,10 @@ "Level": 1 }, { - "Id": "automatic-refresh-configuration", - "Text": "10. Automatic Refresh Configuration", + "Id": "automatic-refresh", + "Text": "10. Automatic Refresh", "Level": 0 }, - { - "Id": "automatic-refresh-is-not-a-security-guarantee", - "Text": "Automatic Refresh Is Not a Security Guarantee", - "Level": 1 - }, { "Id": "validate-current-authentication", "Text": "11. Validate Current Authentication", @@ -354,6 +349,6 @@ "Level": 0 } ], - "SourceHash": "18F45A750C6125AF97026AE10D04E24F8C45DCB3A65DC9C8F04B3F0875FE0412", + "SourceHash": "AB7A8B3BD23CC7BF793F4E8BFCC4920915711BAB58524C1A3E54AC0567107973", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authorization.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authorization.json index 7d7fb69e..f09082a4 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authorization.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/authorization.json @@ -364,6 +364,6 @@ "Level": 0 } ], - "SourceHash": "D14F973C8368A06A394A9B3DE6F13B191FBD8730DA9E9B990023C548FE4F1518", + "SourceHash": "BBEC1F4492A348992F1BC3D17235AA824ADF413CEFD1FC6F846967675E33A3BD", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/automatic-refresh.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/automatic-refresh.json new file mode 100644 index 00000000..2a3f2327 --- /dev/null +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/automatic-refresh.json @@ -0,0 +1,224 @@ +{ + "Slug": "client-sdk/automatic-refresh", + "Title": "Automatic Refresh", + "Html": "\n\u003Cp\u003EAuthentication should not become an application-level scheduling problem.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth provides a coordinated refresh mechanism that can renew authentication before a protected request, recover from supported authentication challenges, or maintain authentication through background execution.\u003C/p\u003E\n\u003Cp\u003EApplications do not need to implement their own token expiration timers, refresh locks, or authentication retry pipelines when using the supported UltimateAuth client operations.\u003C/p\u003E\n\u003Cp\u003EThe same client architecture supports different authentication modes and credential lifecycles without requiring applications to implement a separate refresh strategy for each mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022getting-started\u0022\u003E1. Getting Started\u003C/h2\u003E\n\u003Cp\u003EAutomatic refresh is available through the UltimateAuth Client SDK and its supported platform integrations.\u003C/p\u003E\n\u003Cp\u003EFor Blazor applications, register the client as usual:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EProactive and reactive refresh are enabled by default. Background refresh is opt-in.\u003C/p\u003E\n\u003Cp\u003EThe following configuration makes the defaults explicit:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Proactive = true;\n options.AutoRefresh.Reactive = true;\n options.AutoRefresh.Background = false;\n\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1);\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOnce authentication is established, supported client operations participate in refresh coordination automatically.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe application does not need to check token expiration or explicitly refresh authentication before every request.\u003C/p\u003E\n\u003Cp\u003EFor client registration and configuration, see \u003Ca href=\u0022/docs/configuration/client-options\u0022\u003EClient Options\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022three-automatic-refresh-strategies\u0022\u003E2. Three Automatic Refresh Strategies\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth provides three independently configurable automatic refresh strategies.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EStrategy\u003C/th\u003E\n\u003Cth\u003ETrigger\u003C/th\u003E\n\u003Cth\u003EEnabled by default\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EProactive\u003C/td\u003E\n\u003Ctd\u003EBefore an eligible authenticated request\u003C/td\u003E\n\u003Ctd\u003EYes\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EReactive\u003C/td\u003E\n\u003Ctd\u003EAfter a supported authentication challenge\u003C/td\u003E\n\u003Ctd\u003EYes\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBackground\u003C/td\u003E\n\u003Ctd\u003EWhen the background coordinator reaches its refresh schedule\u003C/td\u003E\n\u003Ctd\u003ENo\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese strategies complement each other. They share the same refresh coordination and credential management infrastructure.\u003C/p\u003E\n\u003Cp\u003EEnabling multiple strategies does not create independent refresh pipelines.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022proactive-refresh\u0022\u003EProactive Refresh\u003C/h3\u003E\n\u003Cp\u003EProactive refresh checks whether authentication is eligible for renewal before sending a supported authenticated request.\u003C/p\u003E\n\u003Cp\u003EWhen refresh is due, the client attempts to renew authentication first.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EApplication request\n |\n v\nIs refresh due?\n |\n \u002B-- No --\u0026gt; Send request\n |\n \u002B-- Yes --\u0026gt; Refresh authentication\n |\n v\n Send request\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis avoids unnecessary authentication challenges when the client already knows that renewal is appropriate.\u003C/p\u003E\n\u003Cp\u003EFor example, when a JWT is approaching expiration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EPOST /auth/refresh -\u0026gt; 204\nGET /api/products -\u0026gt; 200\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWithout proactive refresh, the application might first encounter an expired-token challenge.\u003C/p\u003E\n\u003Cp\u003EProactive refresh is particularly useful for applications that should renew authentication while being used, without continuously refreshing during inactivity.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003ETip: Keep proactive refresh enabled even when background refresh is disabled. Request-driven renewal provides authentication continuity without requiring a continuously running refresh timer.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reactive-refresh\u0022\u003EReactive Refresh\u003C/h3\u003E\n\u003Cp\u003EReactive refresh attempts to recover from a supported authentication challenge.\u003C/p\u003E\n\u003Cp\u003EWhen a protected request is rejected before application execution, the client can attempt refresh and replay the original request using a renewed access token.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EGET /api/products -\u0026gt; 401\nPOST /auth/refresh -\u0026gt; 204\nGET /api/products -\u0026gt; 200\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EReactive refresh is a recovery mechanism rather than the primary refresh schedule.\u003C/p\u003E\n\u003Cp\u003EIt is useful when:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA token expires between preparation and request execution.\u003C/li\u003E\n\u003Cli\u003EAn application resumes after being suspended.\u003C/li\u003E\n\u003Cli\u003EThe server rejects an access token that the client expected to remain valid.\u003C/li\u003E\n\u003Cli\u003EA concurrent request has already renewed the access token.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe client does not blindly retry every unsuccessful request.\u003C/p\u003E\n\u003Cp\u003ERecovery requires a supported authentication challenge and an appropriate access-token lifecycle.\u003C/p\u003E\n\u003Cp\u003EA request is replayed at most once through this recovery pipeline.\u003C/p\u003E\n\u003Cp\u003EThe following responses do not independently trigger authentication recovery:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003E403 Forbidden\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E429 Too Many Requests\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003EArbitrary application-generated \u003Ccode\u003E401\u003C/code\u003E responses\u003C/li\u003E\n\u003Cli\u003ENetwork failures\u003C/li\u003E\n\u003Cli\u003EServer errors\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EReactive recovery currently requires a usable access-token context for safe replay. Cookie-only session authentication does not receive the same automatic replay behavior.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003ETip: Proactive refresh reduces the number of expected authentication challenges. Reactive refresh remains useful as a fallback for expiration races and unexpected authentication rejection.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022background-refresh\u0022\u003EBackground Refresh\u003C/h3\u003E\n\u003Cp\u003EBackground refresh allows the client coordinator to initiate renewal without waiting for an application request.\u003C/p\u003E\n\u003Cp\u003EEnable it explicitly:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Background = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EBackground refresh is useful for applications that need to maintain authentication during periods without protected requests.\u003C/p\u003E\n\u003Cp\u003EExamples include:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EOperational dashboards.\u003C/li\u003E\n\u003Cli\u003EMonitoring applications.\u003C/li\u003E\n\u003Cli\u003ELong-running interactive workspaces.\u003C/li\u003E\n\u003Cli\u003EApplications where users spend significant time editing local state before submitting it.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EBackground refresh requires an active client coordinator and an execution environment capable of running it.\u003C/p\u003E\n\u003Cp\u003EIt cannot guarantee renewal while a browser tab is suspended, a device is offline, an application has been closed, or its execution environment has stopped.\u003C/p\u003E\n\u003Cp\u003EServer-side expiration, revocation, and refresh policies continue to apply.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003ETip: Enable background refresh because your application needs independent authentication renewal, not simply because it supports long-lived sessions.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022how-refresh-timing-works\u0022\u003E3. How Refresh Timing Works\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth uses a shared refresh schedule.\u003C/p\u003E\n\u003Cp\u003EThe schedule adapts to the credential available to the client.\u003C/p\u003E\n\u003Cp\u003EThere are two primary scheduling mechanisms:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EInterval-based scheduling.\u003C/li\u003E\n\u003Cli\u003EJWT expiration-based scheduling.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EApplications do not need to run both mechanisms as independent timers.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interval-based-scheduling\u0022\u003EInterval-Based Scheduling\u003C/h3\u003E\n\u003Cp\u003EWhen the client has an established authentication context without a managed JWT access token, refresh eligibility is determined by \u003Ccode\u003EInterval\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe interval is measured from the establishment of the authenticated schedule or the last successful refresh.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E12:00 Authentication established\n12:02 Protected request\n12:05 Refresh becomes eligible\n12:08 Protected request triggers proactive refresh\n12:08 Refresh succeeds\n12:13 Refresh becomes eligible again\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith background refresh disabled, no refresh request is sent at 12:05 simply because the interval has elapsed.\u003C/p\u003E\n\u003Cp\u003EThe next eligible authenticated request initiates renewal.\u003C/p\u003E\n\u003Cp\u003EThis scheduling mechanism is particularly useful for opaque session authentication.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022jwt-expiration-based-scheduling\u0022\u003EJWT Expiration-Based Scheduling\u003C/h3\u003E\n\u003Cp\u003EWhen a managed JWT access token is available, the client uses its expiration time.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E12:00 Access token issued\n12:09 Refresh becomes eligible\n12:10 Access token expires\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client becomes eligible for refresh one minute before expiration.\u003C/p\u003E\n\u003Cp\u003EIf the configured threshold is greater than or equal to the remaining token lifetime when its schedule is initialized, UltimateAuth reduces the effective threshold to half of that remaining lifetime.\u003C/p\u003E\n\u003Cp\u003EThis prevents short-lived access tokens from immediately entering a continuous refresh cycle.\u003C/p\u003E\n\u003Cp\u003EFor example, a newly received token with a remaining lifetime of 30 seconds and a configured refresh threshold of one minute becomes eligible after approximately 15 seconds.\u003C/p\u003E\n\u003Cp\u003EThe schedule belongs to the credential itself. Repeated validation or repeated schedule checks do not continuously postpone its refresh time.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interval-vs.refreshbeforeexpiration\u0022\u003EInterval vs. RefreshBeforeExpiration\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOption\u003C/th\u003E\n\u003Cth\u003EUsed when\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInterval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication uses an interval-based schedule without a managed JWT\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshBeforeExpiration\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EA managed JWT access token provides an expiration time\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese options describe alternative scheduling mechanisms rather than competing refresh timers.\u003C/p\u003E\n\u003Cp\u003EBoth proactive and background refresh use the applicable shared schedule.\u003C/p\u003E\n\u003Cp\u003EReactive refresh responds to authentication challenges independently of scheduled eligibility.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-modes\u0022\u003E4. Authentication Modes\u003C/h2\u003E\n\u003Cp\u003ERefresh behavior depends on both the authentication mode and the credentials delivered to the client.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003ETypical scheduling\u003C/th\u003E\n\u003Cth\u003ERefresh behavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque\u003C/td\u003E\n\u003Ctd\u003EInterval\u003C/td\u003E\n\u003Ctd\u003EContinue an existing server-side session\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid\u003C/td\u003E\n\u003Ctd\u003EInterval or JWT expiration, depending on the managed credential\u003C/td\u003E\n\u003Ctd\u003EValidate session continuity and rotate refresh credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureJwt\u003C/td\u003E\n\u003Ctd\u003EJWT expiration\u003C/td\u003E\n\u003Ctd\u003ERotate refresh credentials and obtain a replacement access token\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESemiHybrid\u003C/td\u003E\n\u003Ctd\u003EJWT expiration when supported\u003C/td\u003E\n\u003Ctd\u003EJWT renewal with server-managed lifecycle state\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EPureOpaque does not require a separate access-token and refresh-token pair.\u003C/p\u003E\n\u003Cp\u003EIts refresh operation may update recorded session activity and extend session expiration according to server policy.\u003C/p\u003E\n\u003Cp\u003EHybrid combines server-authoritative session state with additional credential lifecycles. The actual client schedule depends on the credential delivered and managed by the client.\u003C/p\u003E\n\u003Cp\u003EPureJwt uses session-independent JWT authentication with a stateful refresh-token lifecycle.\u003C/p\u003E\n\u003Cp\u003ESemiHybrid describes the JWT-based session-backed model. Its complete runtime support is still evolving; applications should not assume that every SemiHybrid scenario is currently available.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022cookie-only-authentication\u0022\u003ECookie-Only Authentication\u003C/h3\u003E\n\u003Cp\u003EAutomatic refresh does not require the application to possess a readable access token.\u003C/p\u003E\n\u003Cp\u003EFor example, PureOpaque can use a server-managed session cookie with interval-based proactive or background refresh.\u003C/p\u003E\n\u003Cp\u003EThe client can initiate the refresh operation without reading the session credential from the cookie.\u003C/p\u003E\n\u003Cp\u003EReactive access-token replay has additional requirements and should not be assumed to work identically for cookie-only authentication.\u003C/p\u003E\n\u003Cp\u003EFor a complete comparison, see \u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022choose-the-right-strategy\u0022\u003E5. Choose the Right Strategy\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022recommended-default\u0022\u003ERecommended Default\u003C/h3\u003E\n\u003Cp\u003EFor most interactive applications:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Proactive = true;\noptions.AutoRefresh.Reactive = true;\noptions.AutoRefresh.Background = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis configuration renews authentication when supported application activity requires it and provides reactive recovery where available.\u003C/p\u003E\n\u003Cp\u003EIt avoids continuously sending refresh requests simply because an application remains open.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022continuous-authentication-maintenance\u0022\u003EContinuous Authentication Maintenance\u003C/h3\u003E\n\u003Cp\u003EFor applications that need independent renewal:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Proactive = true;\noptions.AutoRefresh.Reactive = true;\noptions.AutoRefresh.Background = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe strategies share refresh coordination, so overlapping refresh triggers do not independently rotate the same credential within the client scope.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022reactive-only-recovery\u0022\u003EReactive-Only Recovery\u003C/h3\u003E\n\u003Cp\u003EFor specialized applications that prefer recovery after authentication challenges:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Proactive = false;\noptions.AutoRefresh.Reactive = true;\noptions.AutoRefresh.Background = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis configuration is primarily useful with managed, renewable access tokens.\u003C/p\u003E\n\u003Cp\u003EIt may introduce an additional failed request before successful recovery.\u003C/p\u003E\n\u003Cp\u003EIt is not a replacement for session maintenance in cookie-only opaque authentication.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-refresh-only\u0022\u003EManual Refresh Only\u003C/h3\u003E\n\u003Cp\u003EApplications can disable all three automatic strategies:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Proactive = false;\noptions.AutoRefresh.Reactive = false;\noptions.AutoRefresh.Background = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EExplicit refresh remains available:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDisabling automatic refresh strategies does not necessarily disable initial authentication recovery performed by the client state integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022why-proactive-refresh-is-efficient\u0022\u003E6. Why Proactive Refresh Is Efficient\u003C/h2\u003E\n\u003Cp\u003EConsider an application that remains open for eight hours but receives authenticated application requests during only two hours.\u003C/p\u003E\n\u003Cp\u003EWith a five-minute refresh interval:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EBackground refresh could attempt renewal throughout the eight-hour period.\u003C/li\u003E\n\u003Cli\u003EProactive refresh attempts renewal only when an eligible authenticated request is made.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EUnder simplified conditions with sufficiently frequent requests:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EStrategy\u003C/th\u003E\n\u003Cth style=\u0022text-align: right;\u0022\u003EIllustrative refresh attempts\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EBackground refresh\u003C/td\u003E\n\u003Ctd style=\u0022text-align: right;\u0022\u003E96\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EProactive refresh\u003C/td\u003E\n\u003Ctd style=\u0022text-align: right;\u0022\u003EApproximately 24\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThis represents approximately 75% fewer refresh attempts in this example.\u003C/p\u003E\n\u003Cp\u003EActual results depend on the distribution of requests, successful refresh times, authentication validity, rate limiting, and execution environment.\u003C/p\u003E\n\u003Cp\u003EProactive refresh is request-driven, not a direct measurement of human activity.\u003C/p\u003E\n\u003Cp\u003EAn application that continuously polls protected endpoints may continue renewing authentication even when the user is not interacting with its interface.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003ETip: If preserving meaningful idle expiration is important, review automatic application polling as well as background refresh configuration.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022coordinated-refresh-and-concurrent-requests\u0022\u003E7. Coordinated Refresh and Concurrent Requests\u003C/h2\u003E\n\u003Cp\u003EA common authentication problem occurs when multiple requests discover that an access token needs renewal at the same time.\u003C/p\u003E\n\u003Cp\u003EWithout coordination:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERequest A -\u0026gt; Refresh\nRequest B -\u0026gt; Refresh\nRequest C -\u0026gt; Refresh\nRequest D -\u0026gt; Refresh\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EConcurrent rotation can introduce unnecessary traffic, conflicting credential updates, or refresh-token reuse.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth coordinates refresh through a shared single-flight mechanism.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERequest A --\u002B\nRequest B --\u002B\nRequest C --\u002B--\u0026gt; Shared refresh execution\nRequest D --\u002B |\n v\n Updated authentication\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EConcurrent callers can wait for the same refresh execution rather than independently sending refresh requests.\u003C/p\u003E\n\u003Cp\u003EThe coordination infrastructure is shared by proactive, reactive, background, manual, and initial recovery operations.\u003C/p\u003E\n\u003Cp\u003EThe client also tracks authentication lifecycle and credential changes to prevent stale refresh results from overwriting a newer client authentication context.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA user logs out while a refresh is in progress.\u003C/li\u003E\n\u003Cli\u003EA different user signs in before an earlier refresh completes.\u003C/li\u003E\n\u003Cli\u003EA delayed authentication challenge arrives after another request has already renewed the access token.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe client can reject stale results or reuse an already renewed credential where appropriate.\u003C/p\u003E\n\u003Cp\u003EThis coordination applies within the current client scope.\u003C/p\u003E\n\u003Cp\u003EIt does not provide distributed locking across browser tabs, independent applications, or multiple devices.\u003C/p\u003E\n\u003Cp\u003EServer-side rotation and replay protection remain essential.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/security/refresh-rotation\u0022\u003ERefresh Rotation \u0026amp; Replay Protection\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022safe-authentication-recovery-and-request-replay\u0022\u003E8. Safe Authentication Recovery and Request Replay\u003C/h2\u003E\n\u003Cp\u003EAutomatic request replay must distinguish authentication rejection from application execution.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth uses an authentication recovery response marker for supported authentication challenges.\u003C/p\u003E\n\u003Cp\u003EThe client does not interpret every \u003Ccode\u003E401 Unauthorized\u003C/code\u003E response as permission to replay an operation.\u003C/p\u003E\n\u003Cp\u003EThis distinction matters for requests that modify application state:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.PostAsync\u0026lt;Order\u0026gt;(\u0026quot;/api/orders\u0026quot;, request);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ESupported resource operations can participate in authentication recovery regardless of their HTTP method.\u003C/p\u003E\n\u003Cp\u003EHowever, authentication replay is limited to the supported recovery contract and requires an appropriate renewed credential.\u003C/p\u003E\n\u003Cp\u003EIt is not a general-purpose HTTP retry policy.\u003C/p\u003E\n\u003Cp\u003EApplications should not emit the authentication recovery marker from business logic after performing a mutation.\u003C/p\u003E\n\u003Cp\u003EA custom endpoint that performs side effects before returning an authentication challenge can violate the assumptions required for safe replay.\u003C/p\u003E\n\u003Cp\u003EBusiness-level idempotency remains important for operations that must tolerate retries from networks, proxies, or other infrastructure.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022which-requests-participate\u0022\u003EWhich Requests Participate?\u003C/h3\u003E\n\u003Cp\u003EAutomatic request preparation and recovery are available through:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ESupported authenticated UltimateAuth Client SDK operations.\u003C/li\u003E\n\u003Cli\u003EThe UltimateAuth Resource Client.\u003C/li\u003E\n\u003Cli\u003EOther integrations explicitly connected to the refresh recovery infrastructure.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ENot every authentication flow or SDK endpoint necessarily participates in automatic request replay.\u003C/p\u003E\n\u003Cp\u003EAn arbitrary \u003Ccode\u003EHttpClient\u003C/code\u003E request, direct JavaScript fetch, or server-side service invocation does not automatically enter this pipeline.\u003C/p\u003E\n\u003Cp\u003EFor protected application API integration, see \u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-touch-sliding-expiration-and-idle-timeout\u0022\u003E9. Session Touch, Sliding Expiration, and Idle Timeout\u003C/h2\u003E\n\u003Cp\u003EClient refresh scheduling and server session policies are separate responsibilities.\u003C/p\u003E\n\u003Cp\u003EConsider the following server configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Session.Lifetime = TimeSpan.FromDays(7);\n options.Session.SlidingExpiration = true;\n options.Session.TouchInterval = TimeSpan.FromMinutes(5);\n options.Session.IdleTimeout = TimeSpan.FromDays(4);\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAnd the following client configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(10);\n options.AutoRefresh.Proactive = true;\n options.AutoRefresh.Background = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EEach option serves a different purpose.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOption\u003C/th\u003E\n\u003Cth\u003EResponsibility\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Interval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EClient refresh eligibility\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESession.TouchInterval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EMinimum interval for ordinary server-side session touches\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESession.SlidingExpiration\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EWhether a successful touch can extend session expiration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESession.IdleTimeout\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EMaximum permitted time without recorded session activity\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESession.Lifetime\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESession expiration policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESession.MaxLifetime\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EMaximum chain lifetime when configured\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-does-not-always-touch-a-session\u0022\u003ERefresh Does Not Always Touch a Session\u003C/h3\u003E\n\u003Cp\u003EA refresh request can succeed without changing server-side session state.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Session.TouchInterval = TimeSpan.FromMinutes(5);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIf the client attempts refresh every 30 seconds, ordinary refresh requests may return \u003Ccode\u003ENoOp\u003C/code\u003E until the server touch interval has elapsed.\u003C/p\u003E\n\u003Cp\u003EThis is valid behavior, but it can produce unnecessary refresh traffic.\u003C/p\u003E\n\u003Cp\u003EFor interval-based opaque authentication, a useful starting point is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ETouchInterval \u0026lt;= AutoRefresh.Interval\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is a configuration recommendation rather than a universal requirement.\u003C/p\u003E\n\u003Cp\u003EJWT expiration and refresh-token rotation may require renewal independently of the server touch interval.\u003C/p\u003E\n\u003Cp\u003EExplicit server-side force-touch behavior may also bypass the ordinary touch interval.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022sliding-expiration\u0022\u003ESliding Expiration\u003C/h3\u003E\n\u003Cp\u003EA successful session touch may extend expiration when sliding expiration is enabled.\u003C/p\u003E\n\u003Cp\u003EBoth proactive and background refresh can participate in this behavior.\u003C/p\u003E\n\u003Cp\u003EThe server remains responsible for applying the session lifetime and any configured maximum lifetime.\u003C/p\u003E\n\u003Cp\u003ERefresh cannot revive a session that has already expired or bypass an applicable absolute lifetime limit.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022idle-timeout\u0022\u003EIdle Timeout\u003C/h3\u003E\n\u003Cp\u003EIdle expiration is based on recorded server-side session activity.\u003C/p\u003E\n\u003Cp\u003EIt is not necessarily reset by every protected request.\u003C/p\u003E\n\u003Cp\u003EWith proactive refresh, ordinary requests that occur before refresh eligibility may not update the server\u0027s recorded activity.\u003C/p\u003E\n\u003Cp\u003EConsequently, the recorded idle duration can differ from the time since the user\u0027s last interaction.\u003C/p\u003E\n\u003Cp\u003EConfigure the refresh interval and touch interval with sufficient margin below the idle timeout.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ETouchInterval: 1 minute\nAutoRefresh.Interval: 5 minutes\nIdleTimeout: 30 minutes\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis configuration provides more scheduling margin than using a refresh interval close to the idle timeout.\u003C/p\u003E\n\u003Cp\u003EIt still does not guarantee that a session will remain valid without a timely eligible request.\u003C/p\u003E\n\u003Cp\u003EBackground refresh can keep recorded activity current even when the user is inactive. This may be desirable for continuous workspaces, but it may also prevent idle expiration from reflecting human inactivity.\u003C/p\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003ETip: If the purpose of IdleTimeout is to expire inactive user sessions, prefer request-driven renewal and avoid unnecessary protected polling.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/sessions-devices/session-lifecycle\u0022\u003ESession Model \u0026amp; Lifecycle\u003C/a\u003E and \u003Ca href=\u0022/docs/configuration/server-options\u0022\u003EServer Options\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022rate-limiting-and-refresh-backoff\u0022\u003E10. Rate Limiting and Refresh Backoff\u003C/h2\u003E\n\u003Cp\u003ERefresh is an authentication operation and remains subject to server-side rate limiting.\u003C/p\u003E\n\u003Cp\u003EWhen the server returns \u003Ccode\u003E429 Too Many Requests\u003C/code\u003E, the client observes the applicable retry delay instead of immediately starting another refresh attempt.\u003C/p\u003E\n\u003Cp\u003EA rate-limited refresh does not independently mean that the user has been logged out.\u003C/p\u003E\n\u003Cp\u003EThe client can preserve the existing authentication context while renewal is temporarily unavailable.\u003C/p\u003E\n\u003Cp\u003EWhether an application request can continue depends on the available credential and its validity.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth also applies automatic refresh backoff when a successful refresh does not rotate an existing JWT.\u003C/p\u003E\n\u003Cp\u003EThis prevents repeated proactive or background attempts from creating a tight refresh loop.\u003C/p\u003E\n\u003Cp\u003EA successful refresh response does not make an expired access token valid again.\u003C/p\u003E\n\u003Cp\u003EApplications should handle unsuccessful request results normally and must not assume that every refresh attempt produces usable replacement credentials.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/security/rate-limiting\u0022\u003ERate Limiting\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-refresh-and-authentication-recovery\u0022\u003E11. Manual Refresh and Authentication Recovery\u003C/h2\u003E\n\u003Cp\u003EAutomatic refresh does not remove explicit authentication operations.\u003C/p\u003E\n\u003Cp\u003EApplications can still request refresh directly:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RefreshAsync();\n\nif (result.IsSuccess)\n{\n // Authentication continuation succeeded.\n}\nelse if (result.Outcome == RefreshOutcome.ReauthRequired)\n{\n // Authentication must be established again.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EManual refresh participates in the shared coordination infrastructure.\u003C/p\u003E\n\u003Cp\u003EIt does not bypass server expiration, rotation, revocation, or rate-limiting policies.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-recovery-after-reload\u0022\u003EAuthentication Recovery After Reload\u003C/h3\u003E\n\u003Cp\u003EA client may start without a managed access token, for example after a full browser reload.\u003C/p\u003E\n\u003Cp\u003EWhen a compatible refresh credential remains available, the client can attempt authentication recovery.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Flows.RecoverAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EInitial recovery differs from reactive request replay.\u003C/p\u003E\n\u003Cp\u003EIts purpose is to restore authentication when the client does not currently have usable access material.\u003C/p\u003E\n\u003Cp\u003ERecovery remains subject to server policy and browser credential availability.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/client-sdk/authentication\u0022\u003EAuthentication\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-outcomes\u0022\u003E12. Refresh Outcomes\u003C/h2\u003E\n\u003Cp\u003ERefresh is not synonymous with token rotation.\u003C/p\u003E\n\u003Cp\u003EThe result depends on the authentication mode and the server\u0027s refresh policy.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOutcome\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENoOp\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication continuation succeeded without requiring a session update\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETouched\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERecorded session activity was updated\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERotated\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh credentials were rotated\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGeneric successful refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthRequired\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication cannot safely continue through the attempted refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EApplications should inspect \u003Ccode\u003ERefreshResult.IsSuccess\u003C/code\u003E rather than requiring a particular successful outcome.\u003C/p\u003E\n\u003Cp\u003EDetailed refresh outcomes may depend on the server diagnostics configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Diagnostics.EnableRefreshDetails = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EA generic success result does not necessarily mean that a session was touched or that a token was rotated.\u003C/p\u003E\n\u003Cp\u003EFor server-side execution details, see \u003Ca href=\u0022/docs/auth-flows/refresh-flow\u0022\u003ERefresh Flow\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-diagnostics\u0022\u003E13. Client Diagnostics\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth exposes refresh diagnostics through \u003Ccode\u003EUAuthClientDiagnostics\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EA Blazor component can inject the diagnostics service:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client.Diagnostics\n@inject UAuthClientDiagnostics Diagnostics\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe available counters distinguish refresh operations by their initiating trigger.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EProactiveRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProactive transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReactiveRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReactive transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBackgroundRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBackground transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EManualRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EExplicit manual transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERecoveryRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication recovery transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutomaticRefreshCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECombined proactive, reactive, and background attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshAttemptCount\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETotal transport attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003ECounters represent transport attempts, not individual callers waiting for a shared refresh execution.\u003C/p\u003E\n\u003Cp\u003ELocally deferred operations do not independently increment transport attempt counters.\u003C/p\u003E\n\u003Cp\u003EOutcome counters are also available:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ERefreshTouchedCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ERefreshRotatedCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ERefreshNoOpCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ERefreshSuccessCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ERefreshReauthRequiredCount\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-eligibility-vs.background-scheduling\u0022\u003ERefresh Eligibility vs. Background Scheduling\u003C/h3\u003E\n\u003Cp\u003ETwo diagnostic timestamps describe different aspects of refresh timing.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar eligibleAt = Diagnostics.NextRefreshEligibleAt;\nvar backgroundAt = Diagnostics.NextAutomaticRefreshAt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ENextRefreshEligibleAt\u003C/code\u003E describes the initialized refresh schedule for the current authentication context.\u003C/p\u003E\n\u003Cp\u003E\u003Ccode\u003ENextAutomaticRefreshAt\u003C/code\u003E describes the next attempt scheduled by the background coordinator.\u003C/p\u003E\n\u003Cp\u003EWith proactive refresh enabled and background refresh disabled, the eligibility timestamp can be available while the background timestamp remains null.\u003C/p\u003E\n\u003Cp\u003EEligibility does not guarantee that a request will be sent at that time.\u003C/p\u003E\n\u003Cp\u003ETemporary backoff, rate limiting, authentication changes, and execution environment constraints can affect actual execution.\u003C/p\u003E\n\u003Cp\u003EReading diagnostics does not initiate a refresh or initialize a new JWT refresh schedule.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022observing-changes-in-blazor\u0022\u003EObserving Changes in Blazor\u003C/h3\u003E\n\u003Cp\u003EComponents can subscribe to diagnostic changes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@implements IDisposable\n\n\u0026lt;div\u0026gt;\n Proactive attempts: @Diagnostics.ProactiveRefreshCount\n\u0026lt;/div\u0026gt;\n\n\u0026lt;div\u0026gt;\n Background attempts: @Diagnostics.BackgroundRefreshCount\n\u0026lt;/div\u0026gt;\n\n@code {\n protected override void OnInitialized()\n {\n Diagnostics.Changed \u002B= OnDiagnosticsChanged;\n }\n\n private void OnDiagnosticsChanged()\n {\n _ = InvokeAsync(StateHasChanged);\n }\n\n public void Dispose()\n {\n Diagnostics.Changed -= OnDiagnosticsChanged;\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUse diagnostic notifications to update application displays.\u003C/p\u003E\n\u003Cp\u003EAvoid initiating authentication operations synchronously from diagnostic event handlers.\u003C/p\u003E\n\u003Cp\u003EFor a countdown display, a local UI timer can update the displayed remaining time without sending authentication requests.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-scope\u0022\u003EClient Scope\u003C/h3\u003E\n\u003Cp\u003EDiagnostics describe the current client scope.\u003C/p\u003E\n\u003Cp\u003EThey are not application-wide telemetry, server-wide counters, or persistent per-user audit records.\u003C/p\u003E\n\u003Cp\u003ECounters may accumulate across authentication changes within the same client scope.\u003C/p\u003E\n\u003Cp\u003EApplications that need centralized monitoring should use an appropriate telemetry or logging integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022troubleshooting\u0022\u003E14. Troubleshooting\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-never-runs-when-the-application-is-idle\u0022\u003ERefresh Never Runs When the Application Is Idle\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E Background refresh is disabled.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E This is expected with proactive refresh. Send a supported authenticated request after refresh eligibility is reached, or enable background refresh if independent renewal is required.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-succeeds-but-session-expiration-does-not-change\u0022\u003ERefresh Succeeds but Session Expiration Does Not Change\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The server may return \u003Ccode\u003ENoOp\u003C/code\u003E, sliding expiration may be disabled, or a maximum lifetime may prevent further extension.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Review server session policies and detailed refresh outcomes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022too-many-refresh-requests-return-noop\u0022\u003EToo Many Refresh Requests Return NoOp\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The client refresh interval may be shorter than the server touch interval.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Align the intervals for opaque session authentication.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022a-short-lived-jwt-refreshes-earlier-than-expected\u0022\u003EA Short-Lived JWT Refreshes Earlier Than Expected\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The configured refresh threshold may be greater than the remaining token lifetime.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E UltimateAuth clamps the effective threshold when initializing the schedule. Review the access-token lifetime and refresh threshold together.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022a-401-response-does-not-trigger-reactive-refresh\u0022\u003EA 401 Response Does Not Trigger Reactive Refresh\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The response may not represent a supported authentication challenge, the operation may not participate in recovery, or a renewable managed access token may be unavailable.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Verify the request integration, credential delivery, authentication recovery marker, and reactive configuration.\u003C/p\u003E\n\u003Cp\u003EFor cross-origin browser requests, ensure the required response headers are exposed through CORS.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022background-refresh-is-enabled-but-not-running\u0022\u003EBackground Refresh Is Enabled but Not Running\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The client coordinator may not be started, authentication may not be established, or the application execution environment may be suspended.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Review the client integration and coordinator diagnostics.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-expires-despite-automatic-refresh\u0022\u003EAuthentication Expires Despite Automatic Refresh\u003C/h3\u003E\n\u003Cp\u003E\u003Cstrong\u003ECause:\u003C/strong\u003E The session, refresh token, or authentication chain may have expired or been revoked. A required credential may also be unavailable.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ESolution:\u003C/strong\u003E Handle reauthentication appropriately. Automatic refresh cannot override server security policy.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuration-reference\u0022\u003E15. Configuration Reference\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOption\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EProactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh before eligible authenticated requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERecover from supported authentication challenges\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBackground\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnable independent background refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInterval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E5 minutes\u003C/td\u003E\n\u003Ctd\u003EInterval-based refresh eligibility\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshBeforeExpiration\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E1 minute\u003C/td\u003E\n\u003Ctd\u003EJWT expiration-based refresh threshold\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe effective interval defaults to five minutes after client option configuration.\u003C/p\u003E\n\u003Cp\u003EThe equivalent configuration can be expressed through appsettings.json:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EJSON\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-json\u0022\u003E{\n \u0026quot;UltimateAuth\u0026quot;: {\n \u0026quot;Client\u0026quot;: {\n \u0026quot;AutoRefresh\u0026quot;: {\n \u0026quot;Proactive\u0026quot;: true,\n \u0026quot;Reactive\u0026quot;: true,\n \u0026quot;Background\u0026quot;: false,\n \u0026quot;Interval\u0026quot;: \u0026quot;00:05:00\u0026quot;,\n \u0026quot;RefreshBeforeExpiration\u0026quot;: \u0026quot;00:01:00\u0026quot;\n }\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022summary\u0022\u003ESummary\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth separates authentication renewal from application business logic.\u003C/p\u003E\n\u003Cp\u003EProactive refresh provides efficient request-driven renewal.\u003C/p\u003E\n\u003Cp\u003EReactive refresh provides recovery from supported authentication challenges.\u003C/p\u003E\n\u003Cp\u003EBackground refresh provides independent renewal when the application requires it.\u003C/p\u003E\n\u003Cp\u003EAll strategies share refresh coordination and credential lifecycle management within the current client scope.\u003C/p\u003E\n\u003Cp\u003EThe recommended starting point is proactive and reactive refresh with background refresh disabled.\u003C/p\u003E\n\u003Cp\u003EEnable additional behavior according to the application\u0027s continuity requirements rather than implementing independent authentication timers and retry mechanisms.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022related-documentation\u0022\u003ERelated Documentation\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/authentication\u0022\u003EAuthentication\u003C/a\u003E \u2014 Login, logout, manual refresh, and authentication recovery.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E \u2014 Protected application requests and supported recovery behavior.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/client-options\u0022\u003EClient Options\u003C/a\u003E \u2014 Client configuration reference.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/server-options\u0022\u003EServer Options\u003C/a\u003E \u2014 Server authentication and session policies.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E \u2014 Credential and authentication lifecycle differences.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/auth-flows/refresh-flow\u0022\u003ERefresh Flow\u003C/a\u003E \u2014 Server-side refresh execution.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/sessions-devices/session-lifecycle\u0022\u003ESession Model \u0026amp; Lifecycle\u003C/a\u003E \u2014 Session expiration, touch, and sliding expiration.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/refresh-rotation\u0022\u003ERefresh Rotation \u0026amp; Replay Protection\u003C/a\u003E \u2014 Refresh-token concurrency and replay protection.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/rate-limiting\u0022\u003ERate Limiting\u003C/a\u003E \u2014 Authentication rate limits and server enforcement.\u003C/li\u003E\n\u003C/ul\u003E\n", + "Headings": [ + { + "Id": "getting-started", + "Text": "1. Getting Started", + "Level": 0 + }, + { + "Id": "three-automatic-refresh-strategies", + "Text": "2. Three Automatic Refresh Strategies", + "Level": 0 + }, + { + "Id": "proactive-refresh", + "Text": "Proactive Refresh", + "Level": 1 + }, + { + "Id": "reactive-refresh", + "Text": "Reactive Refresh", + "Level": 1 + }, + { + "Id": "background-refresh", + "Text": "Background Refresh", + "Level": 1 + }, + { + "Id": "how-refresh-timing-works", + "Text": "3. How Refresh Timing Works", + "Level": 0 + }, + { + "Id": "interval-based-scheduling", + "Text": "Interval-Based Scheduling", + "Level": 1 + }, + { + "Id": "jwt-expiration-based-scheduling", + "Text": "JWT Expiration-Based Scheduling", + "Level": 1 + }, + { + "Id": "interval-vs.refreshbeforeexpiration", + "Text": "Interval vs. RefreshBeforeExpiration", + "Level": 1 + }, + { + "Id": "authentication-modes", + "Text": "4. Authentication Modes", + "Level": 0 + }, + { + "Id": "cookie-only-authentication", + "Text": "Cookie-Only Authentication", + "Level": 1 + }, + { + "Id": "choose-the-right-strategy", + "Text": "5. Choose the Right Strategy", + "Level": 0 + }, + { + "Id": "recommended-default", + "Text": "Recommended Default", + "Level": 1 + }, + { + "Id": "continuous-authentication-maintenance", + "Text": "Continuous Authentication Maintenance", + "Level": 1 + }, + { + "Id": "reactive-only-recovery", + "Text": "Reactive-Only Recovery", + "Level": 1 + }, + { + "Id": "manual-refresh-only", + "Text": "Manual Refresh Only", + "Level": 1 + }, + { + "Id": "why-proactive-refresh-is-efficient", + "Text": "6. Why Proactive Refresh Is Efficient", + "Level": 0 + }, + { + "Id": "coordinated-refresh-and-concurrent-requests", + "Text": "7. Coordinated Refresh and Concurrent Requests", + "Level": 0 + }, + { + "Id": "safe-authentication-recovery-and-request-replay", + "Text": "8. Safe Authentication Recovery and Request Replay", + "Level": 0 + }, + { + "Id": "which-requests-participate", + "Text": "Which Requests Participate?", + "Level": 1 + }, + { + "Id": "session-touch-sliding-expiration-and-idle-timeout", + "Text": "9. Session Touch, Sliding Expiration, and Idle Timeout", + "Level": 0 + }, + { + "Id": "refresh-does-not-always-touch-a-session", + "Text": "Refresh Does Not Always Touch a Session", + "Level": 1 + }, + { + "Id": "sliding-expiration", + "Text": "Sliding Expiration", + "Level": 1 + }, + { + "Id": "idle-timeout", + "Text": "Idle Timeout", + "Level": 1 + }, + { + "Id": "rate-limiting-and-refresh-backoff", + "Text": "10. Rate Limiting and Refresh Backoff", + "Level": 0 + }, + { + "Id": "manual-refresh-and-authentication-recovery", + "Text": "11. Manual Refresh and Authentication Recovery", + "Level": 0 + }, + { + "Id": "authentication-recovery-after-reload", + "Text": "Authentication Recovery After Reload", + "Level": 1 + }, + { + "Id": "refresh-outcomes", + "Text": "12. Refresh Outcomes", + "Level": 0 + }, + { + "Id": "client-diagnostics", + "Text": "13. Client Diagnostics", + "Level": 0 + }, + { + "Id": "refresh-eligibility-vs.background-scheduling", + "Text": "Refresh Eligibility vs. Background Scheduling", + "Level": 1 + }, + { + "Id": "observing-changes-in-blazor", + "Text": "Observing Changes in Blazor", + "Level": 1 + }, + { + "Id": "client-scope", + "Text": "Client Scope", + "Level": 1 + }, + { + "Id": "troubleshooting", + "Text": "14. Troubleshooting", + "Level": 0 + }, + { + "Id": "refresh-never-runs-when-the-application-is-idle", + "Text": "Refresh Never Runs When the Application Is Idle", + "Level": 1 + }, + { + "Id": "refresh-succeeds-but-session-expiration-does-not-change", + "Text": "Refresh Succeeds but Session Expiration Does Not Change", + "Level": 1 + }, + { + "Id": "too-many-refresh-requests-return-noop", + "Text": "Too Many Refresh Requests Return NoOp", + "Level": 1 + }, + { + "Id": "a-short-lived-jwt-refreshes-earlier-than-expected", + "Text": "A Short-Lived JWT Refreshes Earlier Than Expected", + "Level": 1 + }, + { + "Id": "a-401-response-does-not-trigger-reactive-refresh", + "Text": "A 401 Response Does Not Trigger Reactive Refresh", + "Level": 1 + }, + { + "Id": "background-refresh-is-enabled-but-not-running", + "Text": "Background Refresh Is Enabled but Not Running", + "Level": 1 + }, + { + "Id": "authentication-expires-despite-automatic-refresh", + "Text": "Authentication Expires Despite Automatic Refresh", + "Level": 1 + }, + { + "Id": "configuration-reference", + "Text": "15. Configuration Reference", + "Level": 0 + }, + { + "Id": "summary", + "Text": "Summary", + "Level": 0 + }, + { + "Id": "related-documentation", + "Text": "Related Documentation", + "Level": 0 + } + ], + "SourceHash": "E337D6157305E084FF8C16F27475CE2F6FB7149B485D85B015C191773D6753BD", + "BuilderVersion": "1" +} \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/credentials.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/credentials.json index 989374dd..89a43be7 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/credentials.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/credentials.json @@ -314,6 +314,6 @@ "Level": 0 } ], - "SourceHash": "1B43969AC7029BFBA504044032854991F7A864A82EEE12176E992D9B9B4CB0FA", + "SourceHash": "4B3AA027344F1EADD546D07064291860B135840D20529647176678116FE5CFD8", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/identifiers.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/identifiers.json index 2c842970..b916207f 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/identifiers.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/identifiers.json @@ -289,6 +289,6 @@ "Level": 0 } ], - "SourceHash": "ADAC74CA7B87824BCE22E4C2EABE20A76E240F2A57AEC96E517FD9498274F0EF", + "SourceHash": "7E9B86D734D78C2E4BB3C7C831ADEB5F838CF43BAC7CD2937C0950450039FE6F", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/overview.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/overview.json index d1540231..3bcf2b0d 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/overview.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/overview.json @@ -1,7 +1,7 @@ { "Slug": "client-sdk/overview", "Title": "Client SDK Overview", - "Html": "\n\u003Cp\u003EThe UltimateAuth Client SDK provides a unified way to integrate authentication, session management, user operations, credentials, and authorization into .NET applications.\u003C/p\u003E\n\u003Cp\u003EInstead of manually constructing requests for every authentication endpoint, applications can use dedicated client services that understand UltimateAuth\u0027s API contracts and authentication workflows.\u003C/p\u003E\n\u003Cp\u003EThe SDK is designed for applications that need to interact with an UltimateAuth server, including Blazor WebAssembly, Blazor Server, and other supported .NET client environments.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThis section is the practical developer guide to using UltimateAuth from application code.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022what-the-client-sdk-provides\u0022\u003EWhat the Client SDK Provides\u003C/h2\u003E\n\u003Cp\u003EThe Client SDK is more than a collection of HTTP methods.\u003C/p\u003E\n\u003Cp\u003EIt brings together several responsibilities:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthentication workflows\u003C/strong\u003E \u2014 Start login, refresh, logout, and other supported authentication operations.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession management\u003C/strong\u003E \u2014 Interact with available session and device management capabilities.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EUser management\u003C/strong\u003E \u2014 Retrieve and manage user information through the appropriate API contracts.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ECredential operations\u003C/strong\u003E \u2014 Manage credentials and initiate supported recovery workflows.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthorization management\u003C/strong\u003E \u2014 Work with roles, permissions, and other exposed authorization operations.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EStructured results\u003C/strong\u003E \u2014 Receive operation results through the SDK\u0027s response contracts.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EClient state integration\u003C/strong\u003E \u2014 Coordinate supported authentication state changes and notifications.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EResource API requests\u003C/strong\u003E \u2014 Access protected application APIs through unified HTTP operations and structured results.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe SDK helps applications interact with UltimateAuth consistently while keeping the server responsible for authentication and authorization enforcement.\u003C/p\u003E\n\u003Cp\u003EIt does not replace server-side security checks.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-client-architecture\u0022\u003EThe Client Architecture\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth separates client responsibilities into specialized services.\u003C/p\u003E\n\u003Cp\u003EThe main client entry point is \u003Ccode\u003EUAuthClient\u003C/code\u003E, which provides access to the SDK\u0027s functional areas.\u003C/p\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EApplication\n |\n v\nIUAuthClient\n |\n \u002B-- Flows\n | Login, logout, refresh, PKCE\n |\n \u002B-- Sessions\n | Sessions and device-associated chains\n |\n \u002B-- Users\n | User information and lifecycle\n |\n \u002B-- Identifiers\n | User identifiers and verification\n |\n \u002B-- Credentials\n | Credential management and recovery\n |\n \u002B-- Authorization\n | Roles, permissions, and access management\n |\n \u002B-- Resource\n Authenticated application API requests\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese represent functional responsibilities. The precise available members and operations depend on the installed packages and supported SDK contracts.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022why-specialized-clients\u0022\u003EWhy Specialized Clients?\u003C/h3\u003E\n\u003Cp\u003EAuthentication-related operations have different requirements.\u003C/p\u003E\n\u003Cp\u003EA login flow may establish authentication state and involve redirects. A user management operation may retrieve or update account information. A credential recovery operation may require additional verification and security handling.\u003C/p\u003E\n\u003Cp\u003EKeeping these responsibilities separate provides a clearer programming model and makes individual APIs easier to discover.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022getting-started-with-uauthclient\u0022\u003EGetting Started with UAuthClient\u003C/h2\u003E\n\u003Cp\u003EIn a supported dependency injection environment, application components can consume the configured UltimateAuth client.\u003C/p\u003E\n\u003Cp\u003EFor example, a Blazor component can receive the client through dependency injection:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@inject UAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOnce configured, the application uses the appropriate client service for the operation it needs.\u003C/p\u003E\n\u003Cp\u003EThe following illustrates the intended programming model:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar user = await UAuthClient.Users.GetMeAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe SDK handles the corresponding client operation and returns its structured result.\u003C/p\u003E\n\u003Cp\u003EBefore using the client, the application must register the appropriate UltimateAuth services and configure its connection to the authentication server.\u003C/p\u003E\n\u003Cp\u003EFor a complete setup, follow the Getting Started guide for your application environment.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022choose-your-application-environment\u0022\u003EChoose Your Application Environment\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports different application architectures, but their authentication and transport requirements are not identical.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-webassembly\u0022\u003EBlazor WebAssembly\u003C/h3\u003E\n\u003Cp\u003EBlazor WebAssembly executes application code in the browser.\u003C/p\u003E\n\u003Cp\u003EThe client communicates with the authentication server and protected APIs through browser-compatible HTTP requests.\u003C/p\u003E\n\u003Cp\u003EBrowser security rules, credential handling, CORS configuration, and authentication state synchronization are relevant to this environment.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server\u0022\u003EBlazor Server\u003C/h3\u003E\n\u003Cp\u003EBlazor Server executes application code on the server while maintaining an interactive connection to the browser.\u003C/p\u003E\n\u003Cp\u003EAuthentication state, cookie behavior, and server-side execution require different considerations from a browser-hosted WebAssembly application.\u003C/p\u003E\n\u003Cp\u003EServer-side code may also invoke application services directly rather than making an HTTP request.\u003C/p\u003E\n\u003Cp\u003ESuch operations still require appropriate server-side authorization enforcement.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-web-applications\u0022\u003EInteractive Web Applications\u003C/h3\u003E\n\u003Cp\u003EApplications combining server rendering and WebAssembly interactivity may have multiple execution environments.\u003C/p\u003E\n\u003Cp\u003EDevelopers should distinguish between operations performed on the server and operations performed in the browser.\u003C/p\u003E\n\u003Cp\u003EShared UI components do not automatically imply identical transport or credential handling.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022other.net-clients\u0022\u003EOther .NET Clients\u003C/h3\u003E\n\u003Cp\u003EOther supported .NET application environments can use the relevant client SDK capabilities according to their platform requirements.\u003C/p\u003E\n\u003Cp\u003ECredential storage, HTTP transport, redirect handling, and authentication state integration may differ from browser applications.\u003C/p\u003E\n\u003Cp\u003EThe SDK\u0027s shared contracts help maintain consistency, while platform-specific integration handles the environment\u0027s requirements.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022working-with-authentication-state\u0022\u003EWorking with Authentication State\u003C/h2\u003E\n\u003Cp\u003EAuthentication is not simply a method call that returns a token.\u003C/p\u003E\n\u003Cp\u003EThe client may need to coordinate several related concerns:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ECompleting the selected authentication flow.\u003C/li\u003E\n\u003Cli\u003EHandling the resulting authentication state.\u003C/li\u003E\n\u003Cli\u003ERenewing authentication when continuation is supported.\u003C/li\u003E\n\u003Cli\u003EReacting to logout or session invalidation.\u003C/li\u003E\n\u003Cli\u003EUpdating application components when relevant state changes.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EUltimateAuth provides client-side abstractions and notifications for supported operations.\u003C/p\u003E\n\u003Cp\u003EFor example, user or credential changes may publish SDK events after a successful operation.\u003C/p\u003E\n\u003Cp\u003EApplications can use the available state integration mechanisms to update their UI without treating every API response as a complete authentication state transition.\u003C/p\u003E\n\u003Cp\u003EThe exact behavior depends on the client environment and configured integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022understanding-sdk-results\u0022\u003EUnderstanding SDK Results\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth client operations use structured response contracts.\u003C/p\u003E\n\u003Cp\u003EApplications should inspect the result of an operation rather than assuming that completing an asynchronous call means the requested action succeeded.\u003C/p\u003E\n\u003Cp\u003EA typical application workflow is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ECall SDK operation\n |\n v\nReceive structured result\n |\n \u002B-- Success\n | |\n | v\n | Continue application workflow\n |\n \u002B-- Failure\n |\n v\n Handle error\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent operations may return different result types.\u003C/p\u003E\n\u003Cp\u003EThe relevant guide for each client service explains its request and response contracts, including how to handle failures.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-events-and-ui-updates\u0022\u003EClient Events and UI Updates\u003C/h2\u003E\n\u003Cp\u003ESome SDK operations can publish notifications when a successful operation changes application-relevant state.\u003C/p\u003E\n\u003Cp\u003EFor example, credential or user management operations may notify subscribers that related information has changed.\u003C/p\u003E\n\u003Cp\u003EThese notifications help decouple an operation from the UI components that react to it.\u003C/p\u003E\n\u003Cp\u003EA component can respond by refreshing its data rather than requiring the caller to manually update every affected view.\u003C/p\u003E\n\u003Cp\u003EHowever, client events are not a security authority.\u003C/p\u003E\n\u003Cp\u003EAn event does not replace server-side validation, and the absence of an event does not prove that the underlying security state has remained unchanged.\u003C/p\u003E\n\u003Cp\u003EApplications should continue to treat the server as authoritative wherever the selected authentication mode requires it.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022calling-protected-resource-apis\u0022\u003ECalling Protected Resource APIs\u003C/h2\u003E\n\u003Cp\u003EAuthentication is only the beginning of an application.\u003C/p\u003E\n\u003Cp\u003EAfter signing in, users still need to retrieve data, create records, and interact with protected application resources.\u003C/p\u003E\n\u003Cp\u003EWithout a unified integration, developers often configure authentication through one SDK and then build a separate HTTP abstraction for their application APIs.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth addresses this through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EResource requests use the same client entry point and structured result model as other UltimateAuth operations.\u003C/p\u003E\n\u003Cp\u003EThe Blazor integration provides browser-based transport, configurable resource origins, credential handling, and request cancellation without requiring application-specific JavaScript wrappers.\u003C/p\u003E\n\u003Cp\u003EThe Resource Client supports GET, POST, PUT, PATCH, and DELETE operations.\u003C/p\u003E\n\u003Cp\u003EIt does not replace server-side authentication or authorization. The receiving Resource API remains responsible for validating requests and enforcing access policies.\u003C/p\u003E\n\u003Cp\u003EFor configuration, examples, security considerations, and supported behavior, see \u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-sdk-guides\u0022\u003EClient SDK Guides\u003C/h2\u003E\n\u003Cp\u003EThe following guides cover the major client responsibilities with practical C# examples.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EGuide\u003C/th\u003E\n\u003Cth\u003EWhat you will learn\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAuthentication\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin, logout, refresh, PKCE, and authentication state handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESession Management\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve, inspect, and manage sessions and device-associated chains\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EUser Management\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve user information and perform supported user lifecycle operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EIdentifiers\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EManage email addresses, usernames, phone numbers, and verification workflows\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ECredentials\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAdd, change, revoke, and recover credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAuthorization\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EWork with roles, permissions, and exposed authorization management operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E\u003C/td\u003E\n\u003Ctd\u003ECall protected application APIs through the unified Resource Client\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EEach guide focuses on a specific developer task and includes the relevant SDK methods, request models, response handling, and implementation considerations.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022recommended-learning-path\u0022\u003ERecommended Learning Path\u003C/h3\u003E\n\u003Cp\u003EIf you are integrating UltimateAuth for the first time, start with \u003Cstrong\u003EAuthentication\u003C/strong\u003E.\u003C/p\u003E\n\u003Cp\u003EOnce login and authentication state handling work correctly, continue with \u003Cstrong\u003EResource API Requests\u003C/strong\u003E to connect authentication to your application\u0027s protected functionality.\u003C/p\u003E\n\u003Cp\u003EAfter that, use the domain-specific guides for the features your application needs.\u003C/p\u003E\n\u003Cp\u003EFor example, an account settings page may require the User Management, Identifiers, and Credentials guides, while an administration panel may additionally require Authorization and Session Management.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-sdk-and-server-responsibilities\u0022\u003EClient SDK and Server Responsibilities\u003C/h2\u003E\n\u003Cp\u003EThe Client SDK simplifies integration, but it does not independently enforce the security of server-side operations.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient responsibility\u003C/th\u003E\n\u003Cth\u003EServer responsibility\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESubmit authentication requests\u003C/td\u003E\n\u003Ctd\u003EValidate authentication requirements\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EManage supported client state\u003C/td\u003E\n\u003Ctd\u003EEstablish and validate authoritative session state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESend protected resource requests\u003C/td\u003E\n\u003Ctd\u003EAuthenticate and authorize protected operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHandle structured responses\u003C/td\u003E\n\u003Ctd\u003EEnforce domain rules and security policies\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EReact to state notifications\u003C/td\u003E\n\u003Ctd\u003EApply revocation and account security controls\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThis separation is particularly important for applications that share UI components across different hosting models.\u003C/p\u003E\n\u003Cp\u003EA shared component can use the same SDK abstractions, while the hosting environment and server determine how authentication material is transported and validated.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-the-client-sdk\u0022\u003EWhen to Use the Client SDK\u003C/h2\u003E\n\u003Cp\u003EUse the Client SDK when building an application that interacts with UltimateAuth\u0027s exposed authentication and management APIs.\u003C/p\u003E\n\u003Cp\u003EIt is generally preferable to manually reproducing the corresponding HTTP contracts because it provides a consistent integration surface and reduces duplicated request-handling code.\u003C/p\u003E\n\u003Cp\u003EDirect endpoint integration may still be appropriate for clients that cannot use the .NET SDK or for specialized interoperability requirements.\u003C/p\u003E\n\u003Cp\u003ERegardless of the client implementation, the same server-side authentication and authorization requirements apply.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cp\u003EContinue with the Client SDK guides to implement real application workflows.\u003C/p\u003E\n\u003Cp\u003EStart with \u003Cstrong\u003EAuthentication\u003C/strong\u003E to configure and use login, refresh, and logout operations.\u003C/p\u003E\n\u003Cp\u003EThen explore session management, user operations, credentials, authorization, and protected resource API integration according to your application\u0027s requirements.\u003C/p\u003E\n\u003Cp\u003EFor the concepts behind these operations, refer to \u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E and \u003Ca href=\u0022/docs/plugin-domains/overview\u0022\u003EPlugin Domains\u003C/a\u003E.\u003C/p\u003E\n", + "Html": "\n\u003Cp\u003EThe UltimateAuth Client SDK provides a unified way to integrate authentication, session management, user operations, credentials, and authorization into .NET applications.\u003C/p\u003E\n\u003Cp\u003EInstead of manually constructing requests for every authentication endpoint, applications can use dedicated client services that understand UltimateAuth\u0027s API contracts and authentication workflows.\u003C/p\u003E\n\u003Cp\u003EThe SDK is designed for applications that need to interact with an UltimateAuth server, including Blazor WebAssembly, Blazor Server, and other supported .NET client environments.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThis section is the practical developer guide to using UltimateAuth from application code.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022what-the-client-sdk-provides\u0022\u003EWhat the Client SDK Provides\u003C/h2\u003E\n\u003Cp\u003EThe Client SDK is more than a collection of HTTP methods.\u003C/p\u003E\n\u003Cp\u003EIt brings together several responsibilities:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthentication workflows\u003C/strong\u003E \u2014 Start login, refresh, logout, and other supported authentication operations.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EAutomatic authentication renewal\u003C/strong\u003E \u2014 Coordinate proactive, reactive, and background refresh without application-specific token timers or authentication retry pipelines.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession management\u003C/strong\u003E \u2014 Interact with available session and device management capabilities.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EUser management\u003C/strong\u003E \u2014 Retrieve and manage user information through the appropriate API contracts.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ECredential operations\u003C/strong\u003E \u2014 Manage credentials and initiate supported recovery workflows.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EAuthorization management\u003C/strong\u003E \u2014 Work with roles, permissions, and other exposed authorization operations.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EStructured results\u003C/strong\u003E \u2014 Receive operation results through the SDK\u0027s response contracts.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EClient state integration\u003C/strong\u003E \u2014 Coordinate supported authentication state changes and notifications.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EResource API requests\u003C/strong\u003E \u2014 Access protected application APIs through unified HTTP operations and structured results.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe SDK helps applications interact with UltimateAuth consistently while keeping the server responsible for authentication and authorization enforcement.\u003C/p\u003E\n\u003Cp\u003EIt does not replace server-side security checks.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-client-architecture\u0022\u003EThe Client Architecture\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth separates client responsibilities into specialized services.\u003C/p\u003E\n\u003Cp\u003EThe main client entry point is \u003Ccode\u003EUAuthClient\u003C/code\u003E, which provides access to the SDK\u0027s functional areas.\u003C/p\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EApplication\n |\n v\nIUAuthClient\n |\n \u002B-- Flows\n | Login, logout, refresh, PKCE\n |\n \u002B-- Sessions\n | Sessions and device-associated chains\n |\n \u002B-- Users\n | User information and lifecycle\n |\n \u002B-- Identifiers\n | User identifiers and verification\n |\n \u002B-- Credentials\n | Credential management and recovery\n |\n \u002B-- Authorization\n | Roles, permissions, and access management\n |\n \u002B-- Resource\n Authenticated application API requests\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese represent functional responsibilities. The precise available members and operations depend on the installed packages and supported SDK contracts.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022why-specialized-clients\u0022\u003EWhy Specialized Clients?\u003C/h3\u003E\n\u003Cp\u003EAuthentication-related operations have different requirements.\u003C/p\u003E\n\u003Cp\u003EA login flow may establish authentication state and involve redirects. A user management operation may retrieve or update account information. A credential recovery operation may require additional verification and security handling.\u003C/p\u003E\n\u003Cp\u003EKeeping these responsibilities separate provides a clearer programming model and makes individual APIs easier to discover.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022getting-started-with-uauthclient\u0022\u003EGetting Started with UAuthClient\u003C/h2\u003E\n\u003Cp\u003EIn a supported dependency injection environment, application components can consume the configured UltimateAuth client.\u003C/p\u003E\n\u003Cp\u003EFor example, a Blazor component can receive the client through dependency injection:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@inject UAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOnce configured, the application uses the appropriate client service for the operation it needs.\u003C/p\u003E\n\u003Cp\u003EThe following illustrates the intended programming model:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar user = await UAuthClient.Users.GetMeAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe SDK handles the corresponding client operation and returns its structured result.\u003C/p\u003E\n\u003Cp\u003EBefore using the client, the application must register the appropriate UltimateAuth services and configure its connection to the authentication server.\u003C/p\u003E\n\u003Cp\u003EFor a complete setup, follow the Getting Started guide for your application environment.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022choose-your-application-environment\u0022\u003EChoose Your Application Environment\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports different application architectures, but their authentication and transport requirements are not identical.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-webassembly\u0022\u003EBlazor WebAssembly\u003C/h3\u003E\n\u003Cp\u003EBlazor WebAssembly executes application code in the browser.\u003C/p\u003E\n\u003Cp\u003EThe client communicates with the authentication server and protected APIs through browser-compatible HTTP requests.\u003C/p\u003E\n\u003Cp\u003EBrowser security rules, credential handling, CORS configuration, and authentication state synchronization are relevant to this environment.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server\u0022\u003EBlazor Server\u003C/h3\u003E\n\u003Cp\u003EBlazor Server executes application code on the server while maintaining an interactive connection to the browser.\u003C/p\u003E\n\u003Cp\u003EAuthentication state, cookie behavior, and server-side execution require different considerations from a browser-hosted WebAssembly application.\u003C/p\u003E\n\u003Cp\u003EServer-side code may also invoke application services directly rather than making an HTTP request.\u003C/p\u003E\n\u003Cp\u003ESuch operations still require appropriate server-side authorization enforcement.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022interactive-web-applications\u0022\u003EInteractive Web Applications\u003C/h3\u003E\n\u003Cp\u003EApplications combining server rendering and WebAssembly interactivity may have multiple execution environments.\u003C/p\u003E\n\u003Cp\u003EDevelopers should distinguish between operations performed on the server and operations performed in the browser.\u003C/p\u003E\n\u003Cp\u003EShared UI components do not automatically imply identical transport or credential handling.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022other.net-clients\u0022\u003EOther .NET Clients\u003C/h3\u003E\n\u003Cp\u003EOther supported .NET application environments can use the relevant client SDK capabilities according to their platform requirements.\u003C/p\u003E\n\u003Cp\u003ECredential storage, HTTP transport, redirect handling, and authentication state integration may differ from browser applications.\u003C/p\u003E\n\u003Cp\u003EThe SDK\u0027s shared contracts help maintain consistency, while platform-specific integration handles the environment\u0027s requirements.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022working-with-authentication-state\u0022\u003EWorking with Authentication State\u003C/h2\u003E\n\u003Cp\u003EAuthentication is not simply a method call that returns a token.\u003C/p\u003E\n\u003Cp\u003EThe client may need to coordinate several related concerns:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ECompleting the selected authentication flow.\u003C/li\u003E\n\u003Cli\u003EHandling the resulting authentication state.\u003C/li\u003E\n\u003Cli\u003ERenewing authentication when continuation is supported.\u003C/li\u003E\n\u003Cli\u003EReacting to logout or session invalidation.\u003C/li\u003E\n\u003Cli\u003EUpdating application components when relevant state changes.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EUltimateAuth provides client-side abstractions and notifications for supported operations.\u003C/p\u003E\n\u003Cp\u003EFor example, user or credential changes may publish SDK events after a successful operation.\u003C/p\u003E\n\u003Cp\u003EApplications can use the available state integration mechanisms to update their UI without treating every API response as a complete authentication state transition.\u003C/p\u003E\n\u003Cp\u003EThe exact behavior depends on the client environment and configured integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022understanding-sdk-results\u0022\u003EUnderstanding SDK Results\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth client operations use structured response contracts.\u003C/p\u003E\n\u003Cp\u003EApplications should inspect the result of an operation rather than assuming that completing an asynchronous call means the requested action succeeded.\u003C/p\u003E\n\u003Cp\u003EA typical application workflow is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ECall SDK operation\n |\n v\nReceive structured result\n |\n \u002B-- Success\n | |\n | v\n | Continue application workflow\n |\n \u002B-- Failure\n |\n v\n Handle error\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent operations may return different result types.\u003C/p\u003E\n\u003Cp\u003EThe relevant guide for each client service explains its request and response contracts, including how to handle failures.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-events-and-ui-updates\u0022\u003EClient Events and UI Updates\u003C/h2\u003E\n\u003Cp\u003ESome SDK operations can publish notifications when a successful operation changes application-relevant state.\u003C/p\u003E\n\u003Cp\u003EFor example, credential or user management operations may notify subscribers that related information has changed.\u003C/p\u003E\n\u003Cp\u003EThese notifications help decouple an operation from the UI components that react to it.\u003C/p\u003E\n\u003Cp\u003EA component can respond by refreshing its data rather than requiring the caller to manually update every affected view.\u003C/p\u003E\n\u003Cp\u003EHowever, client events are not a security authority.\u003C/p\u003E\n\u003Cp\u003EAn event does not replace server-side validation, and the absence of an event does not prove that the underlying security state has remained unchanged.\u003C/p\u003E\n\u003Cp\u003EApplications should continue to treat the server as authoritative wherever the selected authentication mode requires it.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022calling-protected-resource-apis\u0022\u003ECalling Protected Resource APIs\u003C/h2\u003E\n\u003Cp\u003EAuthentication is only the beginning of an application.\u003C/p\u003E\n\u003Cp\u003EAfter signing in, users still need to retrieve data, create records, and interact with protected application resources.\u003C/p\u003E\n\u003Cp\u003EWithout a unified integration, developers often configure authentication through one SDK and then build a separate HTTP abstraction for their application APIs.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth addresses this through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EResource requests use the same client entry point and structured result model as other UltimateAuth operations.\u003C/p\u003E\n\u003Cp\u003EThe Blazor integration provides browser-based transport, configurable resource origins, credential handling, and request cancellation without requiring application-specific JavaScript wrappers.\u003C/p\u003E\n\u003Cp\u003EThe Resource Client supports GET, POST, PUT, PATCH, and DELETE operations.\u003C/p\u003E\n\u003Cp\u003EIt does not replace server-side authentication or authorization. The receiving Resource API remains responsible for validating requests and enforcing access policies.\u003C/p\u003E\n\u003Cp\u003EFor configuration, examples, security considerations, and supported behavior, see \u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-sdk-guides\u0022\u003EClient SDK Guides\u003C/h2\u003E\n\u003Cp\u003EThe following guides cover the major client responsibilities with practical C# examples.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EGuide\u003C/th\u003E\n\u003Cth\u003EWhat you will learn\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAuthentication\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin, logout, refresh, PKCE, and authentication state handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E\u003C/td\u003E\n\u003Ctd\u003EConfigure authentication renewal, refresh scheduling, recovery, and diagnostics\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESession Management\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve, inspect, and manage sessions and device-associated chains\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EUser Management\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve user information and perform supported user lifecycle operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EIdentifiers\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EManage email addresses, usernames, phone numbers, and verification workflows\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ECredentials\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAdd, change, revoke, and recover credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAuthorization\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EWork with roles, permissions, and exposed authorization management operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E\u003C/td\u003E\n\u003Ctd\u003ECall protected application APIs through the unified Resource Client\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EEach guide focuses on a specific developer task and includes the relevant SDK methods, request models, response handling, and implementation considerations.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022recommended-learning-path\u0022\u003ERecommended Learning Path\u003C/h3\u003E\n\u003Cp\u003EIf you are integrating UltimateAuth for the first time, start with \u003Cstrong\u003EAuthentication\u003C/strong\u003E.\u003C/p\u003E\n\u003Cp\u003EContinue with \u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E to understand how UltimateAuth maintains authentication during normal application activity and recovers from supported authentication challenges.\u003C/p\u003E\n\u003Cp\u003EOnce login and authentication state handling work correctly, continue with \u003Cstrong\u003EResource API Requests\u003C/strong\u003E to connect authentication to your application\u0027s protected functionality.\u003C/p\u003E\n\u003Cp\u003EAfter that, use the domain-specific guides for the features your application needs.\u003C/p\u003E\n\u003Cp\u003EFor example, an account settings page may require the User Management, Identifiers, and Credentials guides, while an administration panel may additionally require Authorization and Session Management.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-sdk-and-server-responsibilities\u0022\u003EClient SDK and Server Responsibilities\u003C/h2\u003E\n\u003Cp\u003EThe Client SDK simplifies integration, but it does not independently enforce the security of server-side operations.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient responsibility\u003C/th\u003E\n\u003Cth\u003EServer responsibility\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESubmit authentication requests\u003C/td\u003E\n\u003Ctd\u003EValidate authentication requirements\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EManage supported client state\u003C/td\u003E\n\u003Ctd\u003EEstablish and validate authoritative session state\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESend protected resource requests\u003C/td\u003E\n\u003Ctd\u003EAuthenticate and authorize protected operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHandle structured responses\u003C/td\u003E\n\u003Ctd\u003EEnforce domain rules and security policies\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EReact to state notifications\u003C/td\u003E\n\u003Ctd\u003EApply revocation and account security controls\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThis separation is particularly important for applications that share UI components across different hosting models.\u003C/p\u003E\n\u003Cp\u003EA shared component can use the same SDK abstractions, while the hosting environment and server determine how authentication material is transported and validated.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-the-client-sdk\u0022\u003EWhen to Use the Client SDK\u003C/h2\u003E\n\u003Cp\u003EUse the Client SDK when building an application that interacts with UltimateAuth\u0027s exposed authentication and management APIs.\u003C/p\u003E\n\u003Cp\u003EIt is generally preferable to manually reproducing the corresponding HTTP contracts because it provides a consistent integration surface and reduces duplicated request-handling code.\u003C/p\u003E\n\u003Cp\u003EDirect endpoint integration may still be appropriate for clients that cannot use the .NET SDK or for specialized interoperability requirements.\u003C/p\u003E\n\u003Cp\u003ERegardless of the client implementation, the same server-side authentication and authorization requirements apply.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cp\u003EContinue with the Client SDK guides to implement real application workflows.\u003C/p\u003E\n\u003Cp\u003EStart with \u003Cstrong\u003EAuthentication\u003C/strong\u003E to configure and use login, refresh, and logout operations.\u003C/p\u003E\n\u003Cp\u003EThen explore session management, user operations, credentials, authorization, and protected resource API integration according to your application\u0027s requirements.\u003C/p\u003E\n\u003Cp\u003EFor the concepts behind these operations, refer to \u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E and \u003Ca href=\u0022/docs/plugin-domains/overview\u0022\u003EPlugin Domains\u003C/a\u003E.\u003C/p\u003E\n", "Headings": [ { "Id": "what-the-client-sdk-provides", @@ -94,6 +94,6 @@ "Level": 0 } ], - "SourceHash": "28EB536E721D2C3528E8A2287BCC4F7589B732AC2A192C2EAC862DC31E2154FF", + "SourceHash": "1E5B3D3659E9C3E7EAFFF09BD5E16AE02E0642AD6CBF875EF84EA3BEA60A7111", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/resource-api-requests.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/resource-api-requests.json index b5d128a4..9c350dd7 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/resource-api-requests.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/resource-api-requests.json @@ -1,7 +1,7 @@ { "Slug": "client-sdk/resource-api-requests", "Title": "Resource API Requests", - "Html": "\n\u003Cp\u003E\u003Cstrong\u003EAuthenticate once. Access your application resources through the same unified client.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EAuthentication is only the beginning of an application.\u003C/p\u003E\n\u003Cp\u003EOnce a user signs in, the application still needs to retrieve data, create records, update resources, and communicate with protected APIs.\u003C/p\u003E\n\u003Cp\u003ETraditionally, this introduces another layer of integration work.\u003C/p\u003E\n\u003Cp\u003EDevelopers configure authentication through one library, then build a separate HTTP client to access their application APIs. They must handle credentials, browser restrictions, response parsing, errors, and differences between hosting environments.\u003C/p\u003E\n\u003Cp\u003EThe result is often two separate programming models: one for authentication and another for everything that comes after it.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EUltimateAuth brings these operations together through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EInstead of introducing another client abstraction, applications can use the same UltimateAuth entry point for authentication, identity management, and protected resource requests.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENo custom JavaScript wrapper. No application-specific response type. No separate HTTP client configuration for ordinary authenticated resource requests.\u003C/p\u003E\n\u003Cp\u003EThe goal is straightforward: \u003Cstrong\u003Emake accessing protected application resources feel like a natural continuation of authentication.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-problem-authentication-ends-integration-work-begins\u0022\u003E1. The Problem: Authentication Ends, Integration Work Begins\u003C/h2\u003E\n\u003Cp\u003EConsider a typical application with three components:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Application\n |\n \u002B----\u0026gt; UAuthHub\n | Authentication\n | Sessions\n | Identity\n |\n \u002B----\u0026gt; Resource API\n Products\n Orders\n Application Data\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth handles authentication and identity operations.\u003C/p\u003E\n\u003Cp\u003EBut the application also needs to communicate with its Resource API.\u003C/p\u003E\n\u003Cp\u003EWithout a unified resource client, developers typically need to:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EConfigure an additional HTTP client.\u003C/li\u003E\n\u003Cli\u003EDetermine how authentication credentials should accompany requests.\u003C/li\u003E\n\u003Cli\u003EHandle browser credential policies and cross-origin restrictions.\u003C/li\u003E\n\u003Cli\u003EMaintain device and application profile metadata where applicable.\u003C/li\u003E\n\u003Cli\u003EDeserialize successful responses.\u003C/li\u003E\n\u003Cli\u003ETranslate unsuccessful HTTP responses into application-friendly results.\u003C/li\u003E\n\u003Cli\u003EImplement similar request handling across multiple components.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThese responsibilities are not necessarily complicated individually.\u003C/p\u003E\n\u003Cp\u003EThe problem is their repetition.\u003C/p\u003E\n\u003Cp\u003EA framework that simplifies authentication should not require developers to rebuild the surrounding integration layer every time they need application data.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022a-unified-client-model\u0022\u003EA Unified Client Model\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth already exposes specialized operations through \u003Ccode\u003EIUAuthClient\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClient.Flows\nUAuthClient.Users\nUAuthClient.Sessions\nUAuthClient.Credentials\nUAuthClient.Authorization\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EResource requests follow the same model:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClient.Resource\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis preserves a consistent entry point without mixing application-specific business operations into UltimateAuth\u0027s authentication services.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth does not need to know what a \u003Ccode\u003EProduct\u003C/code\u003E, \u003Ccode\u003EOrder\u003C/code\u003E, or \u003Ccode\u003EInvoice\u003C/code\u003E represents.\u003C/p\u003E\n\u003Cp\u003EIt only needs to provide a predictable way to communicate with the API that owns those resources.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022getting-started\u0022\u003E2. Getting Started\u003C/h2\u003E\n\u003Cp\u003EThe Resource API client is available through the UltimateAuth Client SDK.\u003C/p\u003E\n\u003Cp\u003EFor Blazor applications, register the Blazor client integration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe registration includes the shared client services and the browser-specific resource transport.\u003C/p\u003E\n\u003Cp\u003EYou do not need to register a separate Resource Client.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022inject-iuauthclient\u0022\u003EInject IUAuthClient\u003C/h3\u003E\n\u003Cp\u003EIn a Blazor component:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThen call a protected application endpoint:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe response uses the same structured result model found throughout UltimateAuth.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022what-happens-behind-the-call\u0022\u003EWhat Happens Behind the Call?\u003C/h3\u003E\n\u003Cp\u003EFor the Blazor integration, the request follows this path:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Component\n |\n v\nIUAuthClient.Resource\n |\n v\nResource Client\n |\n v\nUltimateAuth Browser Transport\n |\n v\nProtected Resource API\n |\n v\nUAuthResult\u0026lt;T\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe browser transport handles request construction and browser-specific behavior.\u003C/p\u003E\n\u003Cp\u003EThe Resource API remains responsible for validating authentication and enforcing authorization.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EA successful client request does not bypass server-side security.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022supported-http-operations\u0022\u003E3. Supported HTTP Operations\u003C/h2\u003E\n\u003Cp\u003EThe Resource Client provides five standard HTTP operations.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMethod\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003Cth\u003EReturn type\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EGetAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPostAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECreate or submit a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPutAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReplace or update a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatchAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPartially update a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDeleteAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDelete a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EAll methods accept a relative endpoint and support cancellation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022get\u0022\u003EGET\u003C/h3\u003E\n\u003Cp\u003ERetrieve application data:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ERetrieve a single resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{productId}\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022post\u0022\u003EPOST\u003C/h3\u003E\n\u003Cp\u003ESubmit a new resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar product = new Product\n{\n Name = \u0026quot;Example Product\u0026quot;,\n Price = 29.99m\n};\n\nvar result = await UAuthClient.Resource.PostAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products\u0026quot;, product);\n\nif (result.IsSuccess)\n{\n // Product created successfully.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe request payload is serialized for transport.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022put\u0022\u003EPUT\u003C/h3\u003E\n\u003Cp\u003EUpdate a resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .PutAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{product.Id}\u0026quot;, product);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022patch\u0022\u003EPATCH\u003C/h3\u003E\n\u003Cp\u003ESubmit a partial update:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar changes = new\n{\n Price = 24.99m\n};\n\nvar result = await UAuthClient.Resource\n .PatchAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{productId}\u0026quot;, changes);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client sends the request payload.\u003C/p\u003E\n\u003Cp\u003EThe receiving API determines which partial-update formats and operations it supports.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022delete\u0022\u003EDELETE\u003C/h3\u003E\n\u003Cp\u003EDelete a resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.DeleteAsync($\u0026quot;/api/products/{productId}\u0026quot;);\n\nif (result.IsSuccess)\n{\n // Resource deleted successfully.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUnlike the other methods, \u003Ccode\u003EDeleteAsync\u003C/code\u003E returns the non-generic \u003Ccode\u003EUAuthResult\u003C/code\u003E because the operation does not require a response value.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022consistent-results-with-uauthresult\u0022\u003E4. Consistent Results with UAuthResult\u003C/h2\u003E\n\u003Cp\u003EA common source of unnecessary complexity is response handling.\u003C/p\u003E\n\u003Cp\u003EOne API client returns \u003Ccode\u003EHttpResponseMessage\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EAnother returns a custom response wrapper.\u003C/p\u003E\n\u003Cp\u003EA third throws exceptions for ordinary HTTP failures.\u003C/p\u003E\n\u003Cp\u003EApplications then need different handling logic for operations that are conceptually similar.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth uses \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E to provide a consistent response contract.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products/42\u0026quot;);\n\nif (result.IsSuccess)\n{\n var product = result.Value;\n}\nelse\n{\n var status = result.Status;\n var problem = result.Problem;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022result-properties\u0022\u003EResult Properties\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsSuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EIndicates whether the HTTP operation succeeded\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStatus\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EHTTP response status code\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDeserialized response value for successful generic operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EProblem\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EStructured problem information when available\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EA failed HTTP response does not automatically mean a transport exception.\u003C/p\u003E\n\u003Cp\u003EFor example, an API may return:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003E400 Bad Request\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E401 Unauthorized\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E403 Forbidden\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E404 Not Found\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E409 Conflict\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese responses can be represented through \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe application can inspect the status and decide how to respond.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022structured-problems\u0022\u003EStructured Problems\u003C/h3\u003E\n\u003Cp\u003EWhen an unsuccessful response contains a compatible UltimateAuth problem payload, the Resource Client attempts to deserialize it into \u003Ccode\u003EUAuthProblem\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eif (!result.IsSuccess)\n{\n if (result.Problem is not null)\n {\n // Handle the structured API problem.\n }\n else\n {\n // Handle the HTTP status without a structured problem.\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENot every API returns a compatible problem body.\u003C/p\u003E\n\u003Cp\u003ETherefore, \u003Ccode\u003EProblem\u003C/code\u003E may be \u003Ccode\u003Enull\u003C/code\u003E even when the request failed.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022transport-failures-are-different\u0022\u003ETransport Failures Are Different\u003C/h3\u003E\n\u003Cp\u003ENetwork failures, protocol errors, and request cancellation are different from ordinary unsuccessful HTTP responses.\u003C/p\u003E\n\u003Cp\u003EFor example, an unreachable API does not necessarily produce an HTTP status code.\u003C/p\u003E\n\u003Cp\u003EApplications should distinguish transport exceptions from valid HTTP responses indicating failure.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E standardizes HTTP response handling; it does not guarantee that every network or runtime failure becomes a result object.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022resource-api-configuration\u0022\u003E5. Resource API Configuration\u003C/h2\u003E\n\u003Cp\u003EResource API configuration is part of \u003Ccode\u003EUAuthClientOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe \u003Ccode\u003EResource\u003C/code\u003E options are separate from the authentication endpoint configuration.\u003C/p\u003E\n\u003Cp\u003EThis distinction allows applications to authenticate against one server while accessing resources hosted elsewhere.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022baseaddress\u0022\u003EBaseAddress\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EBaseAddress\u003C/code\u003E identifies the Resource API origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIf \u003Ccode\u003EBaseAddress\u003C/code\u003E is not configured, requests use the application\u0027s current origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EA call such as:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Ethen targets the application\u0027s origin.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022baseaddress-validation\u0022\u003EBaseAddress Validation\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth validates the configured Resource API address.\u003C/p\u003E\n\u003Cp\u003EThe address must:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EBe an absolute HTTP or HTTPS URL.\u003C/li\u003E\n\u003Cli\u003EUse HTTPS, except for loopback development addresses.\u003C/li\u003E\n\u003Cli\u003ERepresent an origin without an additional path.\u003C/li\u003E\n\u003Cli\u003EExclude embedded credentials, query strings, and fragments.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EValid examples:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://api.example.com\nhttps://localhost:7001\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EInvalid examples:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://api.example.com/api\nhttps://api.example.com?version=1\nhttp://api.example.com\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EKeep endpoint paths in individual Resource Client calls:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis separates deployment configuration from application resource paths.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-credential-handling\u0022\u003E6. Browser Credential Handling\u003C/h2\u003E\n\u003Cp\u003EBrowser-based applications do not have unrestricted control over authentication credentials.\u003C/p\u003E\n\u003Cp\u003ECookies, origins, cross-origin requests, and browser security policies all influence how requests are sent.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth exposes credential handling through \u003Ccode\u003EUAuthResourceCredentialsMode\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELet UltimateAuth select the appropriate browser credential policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESameOrigin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESend browser credentials only for same-origin requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInclude\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials for the configured Resource API origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not send browser credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022same-origin-resource-api\u0022\u003ESame-Origin Resource API\u003C/h3\u003E\n\u003Cp\u003EWhen the application and Resource API share an origin:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://app.example.com\nhttps://app.example.com/api/products\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Eyou can use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.SameOrigin;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is appropriate when the Resource API relies on browser credentials available to the application origin.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022separate-resource-api\u0022\u003ESeparate Resource API\u003C/h3\u003E\n\u003Cp\u003EConsider:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EApplication: https://app.example.com\nResource API: https://api.example.com\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor a cross-origin API that requires browser cookies, configure:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Include;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe receiving API must also support the relevant browser security requirements.\u003C/p\u003E\n\u003Cp\u003EFor credentialed cross-origin requests, this typically includes:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EExplicitly permitted origins.\u003C/li\u003E\n\u003Cli\u003EAppropriate CORS configuration.\u003C/li\u003E\n\u003Cli\u003ECompatible cookie attributes and browser policies.\u003C/li\u003E\n\u003Cli\u003EServer-side authentication and authorization.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EConfiguring \u003Ccode\u003EInclude\u003C/code\u003E does not override browser restrictions or guarantee that a cookie is available for the destination.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-omit\u0022\u003EWhen to Use Omit\u003C/h3\u003E\n\u003Cp\u003ESome resource endpoints do not require browser cookies.\u003C/p\u003E\n\u003Cp\u003EFor those cases:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Omit;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis prevents browser credentials from being included in the resource request.\u003C/p\u003E\n\u003Cp\u003EThe API must still enforce whichever authentication mechanism it requires.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECredential transmission is not the same as authorization.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022separate-uauthhub-and-resource-api\u0022\u003E7. Separate UAuthHub and Resource API\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports architectures where authentication and application resources are hosted independently.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E Blazor Application\n |\n \u002B------------\u002B------------\u002B\n | |\n v v\n UAuthHub Resource API\n auth.example.com api.example.com\n | |\n v v\n Authentication Application Data\n Sessions Business Operations\n Identity Authorization\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client can configure both destinations independently:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAuthentication operations use the configured authentication endpoints.\u003C/p\u003E\n\u003Cp\u003EResource operations use the configured Resource API origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar profile = await UAuthClient.Users.GetMeAsync();\n\nvar products = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EBoth operations are accessed through \u003Ccode\u003EIUAuthClient\u003C/code\u003E, but they serve different purposes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-does-not-automatically-protect-an-api\u0022\u003EAuthentication Does Not Automatically Protect an API\u003C/h3\u003E\n\u003Cp\u003EConfiguring a Resource API address does not automatically enable authentication or authorization on that API.\u003C/p\u003E\n\u003Cp\u003EThe Resource API must independently validate incoming requests and enforce its access rules.\u003C/p\u003E\n\u003Cp\u003EFor separate deployments, the Resource API must also be configured to accept and validate the authentication material associated with the selected UltimateAuth authentication mode.\u003C/p\u003E\n\u003Cp\u003EThe Resource Client simplifies communication.\u003C/p\u003E\n\u003Cp\u003EIt does not replace the receiving server\u0027s security responsibilities.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-mode-compatibility\u0022\u003EAuthentication Mode Compatibility\u003C/h3\u003E\n\u003Cp\u003EUAuthHub and Resource APIs are configured independently.\u003C/p\u003E\n\u003Cp\u003EUAuthHub determines which authentication credentials are issued to a client. A Resource API determines which credentials it accepts and how they are validated.\u003C/p\u003E\n\u003Cp\u003EUsing the same UltimateAuth infrastructure does not automatically make all authentication modes interchangeable.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient Credential\u003C/th\u003E\n\u003Cth\u003EResource API Validation\u003C/th\u003E\n\u003Cth\u003ECurrent Support\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque session\u003C/td\u003E\n\u003Ctd\u003ERemote session validation\u003C/td\u003E\n\u003Ctd\u003ESupported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureJwt access token\u003C/td\u003E\n\u003Ctd\u003ELocal JWT validation\u003C/td\u003E\n\u003Ctd\u003ESupported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid session credential\u003C/td\u003E\n\u003Ctd\u003ERemote session validation\u003C/td\u003E\n\u003Ctd\u003ESupported when correctly configured\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid JWT access token\u003C/td\u003E\n\u003Ctd\u003EHybrid-aware JWT validation\u003C/td\u003E\n\u003Ctd\u003ENot yet implemented\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque session\u003C/td\u003E\n\u003Ctd\u003EPureJwt-only validation\u003C/td\u003E\n\u003Ctd\u003ENot supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EA PureJwt Resource API cannot authenticate an opaque session credential as a JWT.\u003C/p\u003E\n\u003Cp\u003ELikewise, configuring a Resource API URL in the client SDK does not automatically exchange session credentials for JWT access tokens.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022credential-delivery\u0022\u003ECredential Delivery\u003C/h3\u003E\n\u003Cp\u003EThe client and Resource API must agree on the credential used for authentication and its transport.\u003C/p\u003E\n\u003Ch4 id=\u0022session-based-resource-apis\u0022\u003ESession-based Resource APIs\u003C/h4\u003E\n\u003Cp\u003EPureOpaque and Hybrid Resource APIs use opaque session credentials.\u003C/p\u003E\n\u003Cp\u003ECookie delivery is the default for incoming session credentials.\u003C/p\u003E\n\u003Cp\u003EThe Resource API validates the selected session through UAuthHub using the configured Hub address.\u003C/p\u003E\n\u003Cp\u003EThe browser must be able to send the session cookie to the Resource API.\u003C/p\u003E\n\u003Ch4 id=\u0022jwt-based-resource-apis\u0022\u003EJWT-based Resource APIs\u003C/h4\u003E\n\u003Cp\u003EPureJwt Resource APIs use JWT access tokens.\u003C/p\u003E\n\u003Cp\u003EThe default Blazor Resource Client attaches the current access token using:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EHTTP\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-http\u0022\u003EAuthorization: Bearer \u0026lt;access-token\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor a Resource API that exclusively uses header-based JWT authentication, browser cookies can be omitted:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Omit;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOmitting browser cookies does not prevent the client from attaching its access-token authorization header.\u003C/p\u003E\n\u003Cp\u003EThis option affects Resource API requests, not authentication or refresh requests sent to UAuthHub.\u003C/p\u003E\n\u003Ch4 id=\u0022credential-compatibility\u0022\u003ECredential compatibility\u003C/h4\u003E\n\u003Cp\u003EA JWT issued in Hybrid mode is not interchangeable with a PureJwt access token.\u003C/p\u003E\n\u003Cp\u003EHybrid-aware JWT validation in separate Resource APIs is not currently implemented.\u003C/p\u003E\n\u003Cp\u003EAuthentication mode selection and credential compatibility remain explicit configuration responsibilities.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt-and-uauthhub-connectivity\u0022\u003EPureJwt and UAuthHub Connectivity\u003C/h3\u003E\n\u003Cp\u003EA PureJwt Resource API does not need to contact UAuthHub to validate each JWT.\u003C/p\u003E\n\u003Cp\u003EHowever, clients still use UAuthHub for login, refresh, and logout operations.\u003C/p\u003E\n\u003Cp\u003EThis separation allows protected APIs to validate access tokens independently while the authentication authority manages refresh-token state.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022device-and-application-profile-metadata\u0022\u003E8. Device and Application Profile Metadata\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth maintains a distinction between user identity, device identity, and client environment.\u003C/p\u003E\n\u003Cp\u003EFor browser resource requests, the transport can propagate UltimateAuth metadata, including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EX-UDID\nX-UAuth-ApplicationProfile\nX-Requested-With\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis keeps resource requests consistent with the UltimateAuth application environment without requiring every application component to construct these headers manually.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Edoes not require the developer to manually retrieve and attach the device identifier.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022metadata-is-not-proof-of-identity\u0022\u003EMetadata Is Not Proof of Identity\u003C/h3\u003E\n\u003Cp\u003EDevice identifiers and application profile values describe request context.\u003C/p\u003E\n\u003Cp\u003EThey are not independent authentication credentials.\u003C/p\u003E\n\u003Cp\u003EA receiving API must not grant access solely because a request declares a particular device identifier or application profile.\u003C/p\u003E\n\u003Cp\u003EThe server remains responsible for validating the user\u0027s authentication state and permissions.\u003C/p\u003E\n\u003Cp\u003EFor more information, see \u003Ca href=\u0022/docs/fundamentals/application-profiles\u0022\u003EApplication Profiles\u003C/a\u003E.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-transport-and-security\u0022\u003E9. Browser Transport and Security\u003C/h2\u003E\n\u003Cp\u003EThe Blazor Resource Client uses UltimateAuth\u0027s browser transport.\u003C/p\u003E\n\u003Cp\u003EThis allows UltimateAuth to apply consistent request behavior without requiring developers to write a separate JavaScript module for their application.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022origin-validation\u0022\u003EOrigin Validation\u003C/h3\u003E\n\u003Cp\u003EResource requests are constrained by the configured Resource API origin.\u003C/p\u003E\n\u003Cp\u003EThe transport validates request destinations rather than allowing arbitrary URLs to bypass the configured resource boundary.\u003C/p\u003E\n\u003Cp\u003EThis helps prevent application code from unintentionally sending credentials or UltimateAuth request metadata to unrelated destinations.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect-protection\u0022\u003ERedirect Protection\u003C/h3\u003E\n\u003Cp\u003EResource requests use redirect protection.\u003C/p\u003E\n\u003Cp\u003EA request should not silently follow a redirect to an unexpected destination while carrying authentication-related context.\u003C/p\u003E\n\u003Cp\u003EApplications should handle unexpected redirects as transport failures rather than assuming the request succeeded.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022request-cancellation\u0022\u003ERequest Cancellation\u003C/h3\u003E\n\u003Cp\u003EResource operations support \u003Ccode\u003ECancellationToken\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));\n\nvar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;, cts.Token);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Blazor transport coordinates cancellation with the underlying browser request.\u003C/p\u003E\n\u003Cp\u003ECancellation is particularly useful when a user navigates away from a page or starts another operation before the previous request completes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-security-still-applies\u0022\u003EBrowser Security Still Applies\u003C/h3\u003E\n\u003Cp\u003EThe Resource Client does not disable browser security mechanisms.\u003C/p\u003E\n\u003Cp\u003ECross-origin requests remain subject to CORS and browser credential policies.\u003C/p\u003E\n\u003Cp\u003ELikewise, origin validation and redirect protection do not replace:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAuthentication validation.\u003C/li\u003E\n\u003Cli\u003EAuthorization policies.\u003C/li\u003E\n\u003Cli\u003ECSRF protection where applicable.\u003C/li\u003E\n\u003Cli\u003EInput validation.\u003C/li\u003E\n\u003Cli\u003EServer-side resource ownership checks.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese responsibilities remain part of the receiving API\u0027s security model.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server-vs.blazor-webassembly\u0022\u003E10. Blazor Server vs. Blazor WebAssembly\u003C/h2\u003E\n\u003Cp\u003EOne of UltimateAuth\u0027s design goals is to provide a consistent client API across supported application environments.\u003C/p\u003E\n\u003Cp\u003EHowever, different hosting models have different execution characteristics.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-webassembly\u0022\u003EBlazor WebAssembly\u003C/h3\u003E\n\u003Cp\u003EBlazor WebAssembly executes application code in the browser.\u003C/p\u003E\n\u003Cp\u003EIt cannot directly invoke server-side application services or access a server database.\u003C/p\u003E\n\u003Cp\u003EA typical application architecture is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor WebAssembly\n |\n v\nIUAuthClient.Resource\n |\n v\nResource API\n |\n v\nApplication Services\n |\n v\nDatabase\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client provides a natural way to access protected application data from this environment.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server\u0022\u003EBlazor Server\u003C/h3\u003E\n\u003Cp\u003EBlazor Server executes component logic on the server.\u003C/p\u003E\n\u003Cp\u003EWhen the application service is available in the same process, a direct service call is often more appropriate.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Server Component\n |\n v\nApplication Service\n |\n v\nDatabase\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar products = await productService.GetAllAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThere is no requirement to introduce an HTTP request simply to use the Resource Client.\u003C/p\u003E\n\u003Cp\u003EHowever, when a Blazor Server application needs to communicate with a separate protected Resource API, it can use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant:\u003C/strong\u003E The current Blazor Resource Client uses browser-based transport, including in Blazor Server applications.\u003C/p\u003E\n\u003Cp\u003EThe HTTP request is initiated by the user\u0027s browser, not by a server-side \u003Ccode\u003EHttpClient\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor server-to-server communication, use an appropriate server-side HTTP integration and authentication mechanism.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-same-client-api-different-application-architectures\u0022\u003EThe Same Client API, Different Application Architectures\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth aims to make client integration consistent without forcing every application into the same deployment model.\u003C/p\u003E\n\u003Cp\u003EThe goal is not to replace direct application service calls.\u003C/p\u003E\n\u003Cp\u003EThe goal is to remove unnecessary integration work whenever an HTTP resource request is actually needed.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022handling-unauthorized-responses\u0022\u003E11. Handling Unauthorized Responses\u003C/h2\u003E\n\u003Cp\u003EAn authenticated session may expire or become invalid while an application is running.\u003C/p\u003E\n\u003Cp\u003EWhen a Resource API returns \u003Ccode\u003E401 Unauthorized\u003C/code\u003E, the Resource Client exposes the unsuccessful HTTP response through its standard result contract.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (!result.IsSuccess \u0026amp;\u0026amp; result.Status == 401)\n{\n // Authentication may need to be renewed.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh-and-retry\u0022\u003EAutomatic Refresh and Retry\u003C/h3\u003E\n\u003Cp\u003EThe current Resource Client does not automatically refresh authentication and retry a request after receiving a \u003Ccode\u003E401\u003C/code\u003E response.\u003C/p\u003E\n\u003Cp\u003EThis behavior is intentionally outside the initial Resource API implementation.\u003C/p\u003E\n\u003Cp\u003EApplications should not assume that an unsuccessful request has been retried.\u003C/p\u003E\n\u003Cp\u003EAuthentication renewal and retry policies require careful handling, particularly for requests that modify application state.\u003C/p\u003E\n\u003Cp\u003EFuture improvements may provide additional coordination between resource requests and authentication lifecycle management.\u003C/p\u003E\n\u003Cp\u003EUntil then, applications should handle unauthorized responses according to their authentication flow and UI requirements.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022organizing-application-resource-services\u0022\u003E12. Organizing Application Resource Services\u003C/h2\u003E\n\u003Cp\u003EAlthough Resource Client operations can be called directly from components, larger applications often benefit from small, domain-specific services.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing CodeBeam.UltimateAuth.Client;\nusing CodeBeam.UltimateAuth.Core.Contracts;\n\npublic sealed class ProductApiService(IUAuthClient client)\n{\n public Task\u0026lt;UAuthResult\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;\u0026gt; GetAllAsync()\n =\u0026gt; client.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; GetAsync(int id)\n =\u0026gt; client.Resource.GetAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{id}\u0026quot;);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; CreateAsync(Product product)\n =\u0026gt; client.Resource.PostAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products\u0026quot;, product);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; UpdateAsync(int id, Product product)\n =\u0026gt; client.Resource.PutAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{id}\u0026quot;, product);\n\n public Task\u0026lt;UAuthResult\u0026gt; DeleteAsync(int id)\n =\u0026gt; client.Resource.DeleteAsync($\u0026quot;/api/products/{id}\u0026quot;);\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis approach keeps application-specific endpoints and operations in one place.\u003C/p\u003E\n\u003Cp\u003EThe service does not need to implement:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA custom HTTP transport.\u003C/li\u003E\n\u003Cli\u003EBrowser credential handling.\u003C/li\u003E\n\u003Cli\u003EDevice metadata propagation.\u003C/li\u003E\n\u003Cli\u003EJSON response deserialization.\u003C/li\u003E\n\u003Cli\u003EA separate response wrapper.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThose responsibilities remain with UltimateAuth.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022keep-the-standard-result\u0022\u003EKeep the Standard Result\u003C/h3\u003E\n\u003Cp\u003ENotice that \u003Ccode\u003EProductApiService\u003C/code\u003E returns \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E directly.\u003C/p\u003E\n\u003Cp\u003EThere is no need to create another response type merely to wrap the same status, value, and problem information.\u003C/p\u003E\n\u003Cp\u003EThis keeps the application aligned with the UltimateAuth SDK.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-services-still-own-business-logic\u0022\u003EApplication Services Still Own Business Logic\u003C/h3\u003E\n\u003Cp\u003EThe Resource Client does not attempt to understand application-specific business rules.\u003C/p\u003E\n\u003Cp\u003EA \u003Ccode\u003EProductApiService\u003C/code\u003E can organize product-related operations, but the Resource API remains responsible for validating product data, enforcing ownership, and authorizing changes.\u003C/p\u003E\n\u003Cp\u003EThis separation keeps UltimateAuth focused on the infrastructure it can provide consistently.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022design-philosophy\u0022\u003E13. Design Philosophy\u003C/h2\u003E\n\u003Cp\u003EThe Resource Client follows the same principle as the rest of UltimateAuth:\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EComplexity should be handled by the framework when it is common, predictable, and independent of application business logic.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EDevelopers should not need to repeatedly solve browser transport, credential configuration, device metadata, and response handling simply because their application has its own API.\u003C/p\u003E\n\u003Cp\u003EAt the same time, a framework should not hide important security boundaries or take ownership of application-specific decisions.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth therefore provides:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA unified client entry point.\u003C/li\u003E\n\u003Cli\u003EFamiliar HTTP operations.\u003C/li\u003E\n\u003Cli\u003EConsistent result contracts.\u003C/li\u003E\n\u003Cli\u003EConfigurable resource origins and credential policies.\u003C/li\u003E\n\u003Cli\u003EBrowser-aware transport behavior.\u003C/li\u003E\n\u003Cli\u003EExplicit server-side security responsibilities.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe result is a simpler developer experience without requiring applications to abandon their existing architecture.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Authentication\nawait UAuthClient.Flows.RefreshAsync();\n\n// Identity\nvar user = await UAuthClient.Users.GetMeAsync();\n\n// Sessions\nvar sessions = await UAuthClient.Sessions.GetMyChainsAsync(\n new PageRequest\n {\n PageNumber = 1,\n PageSize = 10\n });\n\n// Application resources\nvar products = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent responsibilities. One consistent client model.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EUltimateAuth does not stop at authentication. It helps applications use authentication without rebuilding the integration layer around it.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022related-documentation\u0022\u003ERelated Documentation\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/overview\u0022\u003EClient SDK Overview\u003C/a\u003E \u2014 Understand the unified client architecture.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/client-options\u0022\u003EClient Options\u003C/a\u003E \u2014 Configure application profiles, authentication endpoints, and resource options.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/authentication\u0022\u003EAuthentication\u003C/a\u003E \u2014 Work with authentication flows and session renewal.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/application-profiles\u0022\u003EApplication Profiles\u003C/a\u003E \u2014 Understand runtime-specific authentication behavior.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/getting-started/real-world-setup\u0022\u003EReal-World Setup\u003C/a\u003E \u2014 Configure Blazor applications, UAuthHub, and separate Resource APIs.\u003C/li\u003E\n\u003C/ul\u003E\n", + "Html": "\n\u003Cp\u003E\u003Cstrong\u003EAuthenticate once. Access your application resources through the same unified client.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EAuthentication is only the beginning of an application.\u003C/p\u003E\n\u003Cp\u003EOnce a user signs in, the application still needs to retrieve data, create records, update resources, and communicate with protected APIs.\u003C/p\u003E\n\u003Cp\u003ETraditionally, this introduces another layer of integration work.\u003C/p\u003E\n\u003Cp\u003EDevelopers configure authentication through one library, then build a separate HTTP client to access their application APIs. They must handle credentials, browser restrictions, response parsing, errors, and differences between hosting environments.\u003C/p\u003E\n\u003Cp\u003EThe result is often two separate programming models: one for authentication and another for everything that comes after it.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EUltimateAuth brings these operations together through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EInstead of introducing another client abstraction, applications can use the same UltimateAuth entry point for authentication, identity management, and protected resource requests.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENo custom JavaScript wrapper. No application-specific response type. No separate HTTP client configuration for ordinary authenticated resource requests.\u003C/p\u003E\n\u003Cp\u003EThe goal is straightforward: \u003Cstrong\u003Emake accessing protected application resources feel like a natural continuation of authentication.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-problem-authentication-ends-integration-work-begins\u0022\u003E1. The Problem: Authentication Ends, Integration Work Begins\u003C/h2\u003E\n\u003Cp\u003EConsider a typical application with three components:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Application\n |\n \u002B----\u0026gt; UAuthHub\n | Authentication\n | Sessions\n | Identity\n |\n \u002B----\u0026gt; Resource API\n Products\n Orders\n Application Data\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth handles authentication and identity operations.\u003C/p\u003E\n\u003Cp\u003EBut the application also needs to communicate with its Resource API.\u003C/p\u003E\n\u003Cp\u003EWithout a unified resource client, developers typically need to:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EConfigure an additional HTTP client.\u003C/li\u003E\n\u003Cli\u003EDetermine how authentication credentials should accompany requests.\u003C/li\u003E\n\u003Cli\u003EHandle browser credential policies and cross-origin restrictions.\u003C/li\u003E\n\u003Cli\u003EMaintain device and application profile metadata where applicable.\u003C/li\u003E\n\u003Cli\u003EDeserialize successful responses.\u003C/li\u003E\n\u003Cli\u003ETranslate unsuccessful HTTP responses into application-friendly results.\u003C/li\u003E\n\u003Cli\u003EImplement similar request handling across multiple components.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThese responsibilities are not necessarily complicated individually.\u003C/p\u003E\n\u003Cp\u003EThe problem is their repetition.\u003C/p\u003E\n\u003Cp\u003EA framework that simplifies authentication should not require developers to rebuild the surrounding integration layer every time they need application data.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022a-unified-client-model\u0022\u003EA Unified Client Model\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth already exposes specialized operations through \u003Ccode\u003EIUAuthClient\u003C/code\u003E:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClient.Flows\nUAuthClient.Users\nUAuthClient.Sessions\nUAuthClient.Credentials\nUAuthClient.Authorization\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EResource requests follow the same model:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClient.Resource\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis preserves a consistent entry point without mixing application-specific business operations into UltimateAuth\u0027s authentication services.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth does not need to know what a \u003Ccode\u003EProduct\u003C/code\u003E, \u003Ccode\u003EOrder\u003C/code\u003E, or \u003Ccode\u003EInvoice\u003C/code\u003E represents.\u003C/p\u003E\n\u003Cp\u003EIt only needs to provide a predictable way to communicate with the API that owns those resources.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022getting-started\u0022\u003E2. Getting Started\u003C/h2\u003E\n\u003Cp\u003EThe Resource API client is available through the UltimateAuth Client SDK.\u003C/p\u003E\n\u003Cp\u003EFor Blazor applications, register the Blazor client integration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe registration includes the shared client services and the browser-specific resource transport.\u003C/p\u003E\n\u003Cp\u003EYou do not need to register a separate Resource Client.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022inject-iuauthclient\u0022\u003EInject IUAuthClient\u003C/h3\u003E\n\u003Cp\u003EIn a Blazor component:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003ERazor\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-razor\u0022\u003E@using CodeBeam.UltimateAuth.Client\n@inject IUAuthClient UAuthClient\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThen call a protected application endpoint:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe response uses the same structured result model found throughout UltimateAuth.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022what-happens-behind-the-call\u0022\u003EWhat Happens Behind the Call?\u003C/h3\u003E\n\u003Cp\u003EFor the Blazor integration, the request follows this path:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Component\n |\n v\nIUAuthClient.Resource\n |\n v\nResource Client\n |\n v\nUltimateAuth Browser Transport\n |\n v\nProtected Resource API\n |\n v\nUAuthResult\u0026lt;T\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe browser transport handles request construction and browser-specific behavior.\u003C/p\u003E\n\u003Cp\u003EThe Resource API remains responsible for validating authentication and enforcing authorization.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EA successful client request does not bypass server-side security.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022supported-http-operations\u0022\u003E3. Supported HTTP Operations\u003C/h2\u003E\n\u003Cp\u003EThe Resource Client provides five standard HTTP operations.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMethod\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003Cth\u003EReturn type\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EGetAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERetrieve a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPostAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECreate or submit a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPutAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReplace or update a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatchAsync\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPartially update a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDeleteAsync\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDelete a resource\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthResult\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EAll methods accept a relative endpoint and support cancellation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022get\u0022\u003EGET\u003C/h3\u003E\n\u003Cp\u003ERetrieve application data:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess \u0026amp;\u0026amp; result.Value is not null)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ERetrieve a single resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{productId}\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022post\u0022\u003EPOST\u003C/h3\u003E\n\u003Cp\u003ESubmit a new resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar product = new Product\n{\n Name = \u0026quot;Example Product\u0026quot;,\n Price = 29.99m\n};\n\nvar result = await UAuthClient.Resource.PostAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products\u0026quot;, product);\n\nif (result.IsSuccess)\n{\n // Product created successfully.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe request payload is serialized for transport.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022put\u0022\u003EPUT\u003C/h3\u003E\n\u003Cp\u003EUpdate a resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .PutAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{product.Id}\u0026quot;, product);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022patch\u0022\u003EPATCH\u003C/h3\u003E\n\u003Cp\u003ESubmit a partial update:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar changes = new\n{\n Price = 24.99m\n};\n\nvar result = await UAuthClient.Resource\n .PatchAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{productId}\u0026quot;, changes);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client sends the request payload.\u003C/p\u003E\n\u003Cp\u003EThe receiving API determines which partial-update formats and operations it supports.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022delete\u0022\u003EDELETE\u003C/h3\u003E\n\u003Cp\u003EDelete a resource:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.DeleteAsync($\u0026quot;/api/products/{productId}\u0026quot;);\n\nif (result.IsSuccess)\n{\n // Resource deleted successfully.\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUnlike the other methods, \u003Ccode\u003EDeleteAsync\u003C/code\u003E returns the non-generic \u003Ccode\u003EUAuthResult\u003C/code\u003E because the operation does not require a response value.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022consistent-results-with-uauthresult\u0022\u003E4. Consistent Results with UAuthResult\u003C/h2\u003E\n\u003Cp\u003EA common source of unnecessary complexity is response handling.\u003C/p\u003E\n\u003Cp\u003EOne API client returns \u003Ccode\u003EHttpResponseMessage\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EAnother returns a custom response wrapper.\u003C/p\u003E\n\u003Cp\u003EA third throws exceptions for ordinary HTTP failures.\u003C/p\u003E\n\u003Cp\u003EApplications then need different handling logic for operations that are conceptually similar.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth uses \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E to provide a consistent response contract.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products/42\u0026quot;);\n\nif (result.IsSuccess)\n{\n var product = result.Value;\n}\nelse\n{\n var status = result.Status;\n var problem = result.Problem;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022result-properties\u0022\u003EResult Properties\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EIsSuccess\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EIndicates whether the HTTP operation succeeded\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStatus\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EHTTP response status code\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDeserialized response value for successful generic operations\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EProblem\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EStructured problem information when available\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EA failed HTTP response does not automatically mean a transport exception.\u003C/p\u003E\n\u003Cp\u003EFor example, an API may return:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003E400 Bad Request\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E401 Unauthorized\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E403 Forbidden\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E404 Not Found\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003E409 Conflict\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese responses can be represented through \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe application can inspect the status and decide how to respond.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022structured-problems\u0022\u003EStructured Problems\u003C/h3\u003E\n\u003Cp\u003EWhen an unsuccessful response contains a compatible UltimateAuth problem payload, the Resource Client attempts to deserialize it into \u003Ccode\u003EUAuthProblem\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eif (!result.IsSuccess)\n{\n if (result.Problem is not null)\n {\n // Handle the structured API problem.\n }\n else\n {\n // Handle the HTTP status without a structured problem.\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENot every API returns a compatible problem body.\u003C/p\u003E\n\u003Cp\u003ETherefore, \u003Ccode\u003EProblem\u003C/code\u003E may be \u003Ccode\u003Enull\u003C/code\u003E even when the request failed.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022transport-failures-are-different\u0022\u003ETransport Failures Are Different\u003C/h3\u003E\n\u003Cp\u003ENetwork failures, protocol errors, and request cancellation are different from ordinary unsuccessful HTTP responses.\u003C/p\u003E\n\u003Cp\u003EFor example, an unreachable API does not necessarily produce an HTTP status code.\u003C/p\u003E\n\u003Cp\u003EApplications should distinguish transport exceptions from valid HTTP responses indicating failure.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003E\u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E standardizes HTTP response handling; it does not guarantee that every network or runtime failure becomes a result object.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022resource-api-configuration\u0022\u003E5. Resource API Configuration\u003C/h2\u003E\n\u003Cp\u003EResource API configuration is part of \u003Ccode\u003EUAuthClientOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe \u003Ccode\u003EResource\u003C/code\u003E options are separate from the authentication endpoint configuration.\u003C/p\u003E\n\u003Cp\u003EThis distinction allows applications to authenticate against one server while accessing resources hosted elsewhere.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022baseaddress\u0022\u003EBaseAddress\u003C/h3\u003E\n\u003Cp\u003E\u003Ccode\u003EBaseAddress\u003C/code\u003E identifies the Resource API origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIf \u003Ccode\u003EBaseAddress\u003C/code\u003E is not configured, requests use the application\u0027s current origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EA call such as:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Ethen targets the application\u0027s origin.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022baseaddress-validation\u0022\u003EBaseAddress Validation\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth validates the configured Resource API address.\u003C/p\u003E\n\u003Cp\u003EThe address must:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EBe an absolute HTTP or HTTPS URL.\u003C/li\u003E\n\u003Cli\u003EUse HTTPS, except for loopback development addresses.\u003C/li\u003E\n\u003Cli\u003ERepresent an origin without an additional path.\u003C/li\u003E\n\u003Cli\u003EExclude embedded credentials, query strings, and fragments.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EValid examples:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://api.example.com\nhttps://localhost:7001\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EInvalid examples:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://api.example.com/api\nhttps://api.example.com?version=1\nhttp://api.example.com\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EKeep endpoint paths in individual Resource Client calls:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis separates deployment configuration from application resource paths.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-credential-handling\u0022\u003E6. Browser Credential Handling\u003C/h2\u003E\n\u003Cp\u003EBrowser-based applications do not have unrestricted control over authentication credentials.\u003C/p\u003E\n\u003Cp\u003ECookies, origins, cross-origin requests, and browser security policies all influence how requests are sent.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth exposes credential handling through \u003Ccode\u003EUAuthResourceCredentialsMode\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELet UltimateAuth select the appropriate browser credential policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESameOrigin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ESend browser credentials only for same-origin requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInclude\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials for the configured Resource API origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not send browser credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022same-origin-resource-api\u0022\u003ESame-Origin Resource API\u003C/h3\u003E\n\u003Cp\u003EWhen the application and Resource API share an origin:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003Ehttps://app.example.com\nhttps://app.example.com/api/products\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Eyou can use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.SameOrigin;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is appropriate when the Resource API relies on browser credentials available to the application origin.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022separate-resource-api\u0022\u003ESeparate Resource API\u003C/h3\u003E\n\u003Cp\u003EConsider:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EApplication: https://app.example.com\nResource API: https://api.example.com\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor a cross-origin API that requires browser cookies, configure:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Include;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe receiving API must also support the relevant browser security requirements.\u003C/p\u003E\n\u003Cp\u003EFor credentialed cross-origin requests, this typically includes:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EExplicitly permitted origins.\u003C/li\u003E\n\u003Cli\u003EAppropriate CORS configuration.\u003C/li\u003E\n\u003Cli\u003ECompatible cookie attributes and browser policies.\u003C/li\u003E\n\u003Cli\u003EServer-side authentication and authorization.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EConfiguring \u003Ccode\u003EInclude\u003C/code\u003E does not override browser restrictions or guarantee that a cookie is available for the destination.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022when-to-use-omit\u0022\u003EWhen to Use Omit\u003C/h3\u003E\n\u003Cp\u003ESome resource endpoints do not require browser cookies.\u003C/p\u003E\n\u003Cp\u003EFor those cases:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Omit;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis prevents browser credentials from being included in the resource request.\u003C/p\u003E\n\u003Cp\u003EThe API must still enforce whichever authentication mechanism it requires.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ECredential transmission is not the same as authorization.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022separate-uauthhub-and-resource-api\u0022\u003E7. Separate UAuthHub and Resource API\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports architectures where authentication and application resources are hosted independently.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E Blazor Application\n |\n \u002B------------\u002B------------\u002B\n | |\n v v\n UAuthHub Resource API\n auth.example.com api.example.com\n | |\n v v\n Authentication Application Data\n Sessions Business Operations\n Identity Authorization\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client can configure both destinations independently:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAuthentication operations use the configured authentication endpoints.\u003C/p\u003E\n\u003Cp\u003EResource operations use the configured Resource API origin.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar profile = await UAuthClient.Users.GetMeAsync();\n\nvar products = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EBoth operations are accessed through \u003Ccode\u003EIUAuthClient\u003C/code\u003E, but they serve different purposes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-does-not-automatically-protect-an-api\u0022\u003EAuthentication Does Not Automatically Protect an API\u003C/h3\u003E\n\u003Cp\u003EConfiguring a Resource API address does not automatically enable authentication or authorization on that API.\u003C/p\u003E\n\u003Cp\u003EThe Resource API must independently validate incoming requests and enforce its access rules.\u003C/p\u003E\n\u003Cp\u003EFor separate deployments, the Resource API must also be configured to accept and validate the authentication material associated with the selected UltimateAuth authentication mode.\u003C/p\u003E\n\u003Cp\u003EThe Resource Client simplifies communication.\u003C/p\u003E\n\u003Cp\u003EIt does not replace the receiving server\u0027s security responsibilities.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-mode-compatibility\u0022\u003EAuthentication Mode Compatibility\u003C/h3\u003E\n\u003Cp\u003EUAuthHub and Resource APIs are configured independently.\u003C/p\u003E\n\u003Cp\u003EUAuthHub determines which authentication credentials are issued to a client. A Resource API determines which credentials it accepts and how they are validated.\u003C/p\u003E\n\u003Cp\u003EUsing the same UltimateAuth infrastructure does not automatically make all authentication modes interchangeable.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EClient Credential\u003C/th\u003E\n\u003Cth\u003EResource API Validation\u003C/th\u003E\n\u003Cth\u003ECurrent Support\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque session\u003C/td\u003E\n\u003Ctd\u003ERemote session validation\u003C/td\u003E\n\u003Ctd\u003ESupported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureJwt access token\u003C/td\u003E\n\u003Ctd\u003ELocal JWT validation\u003C/td\u003E\n\u003Ctd\u003ESupported\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid session credential\u003C/td\u003E\n\u003Ctd\u003ERemote session validation\u003C/td\u003E\n\u003Ctd\u003ESupported when correctly configured\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EHybrid JWT access token\u003C/td\u003E\n\u003Ctd\u003EHybrid-aware JWT validation\u003C/td\u003E\n\u003Ctd\u003ENot yet implemented\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPureOpaque session\u003C/td\u003E\n\u003Ctd\u003EPureJwt-only validation\u003C/td\u003E\n\u003Ctd\u003ENot supported\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EA PureJwt Resource API cannot authenticate an opaque session credential as a JWT.\u003C/p\u003E\n\u003Cp\u003ELikewise, configuring a Resource API URL in the client SDK does not automatically exchange session credentials for JWT access tokens.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022credential-delivery\u0022\u003ECredential Delivery\u003C/h3\u003E\n\u003Cp\u003EThe client and Resource API must agree on the credential used for authentication and its transport.\u003C/p\u003E\n\u003Ch4 id=\u0022session-based-resource-apis\u0022\u003ESession-based Resource APIs\u003C/h4\u003E\n\u003Cp\u003EPureOpaque and Hybrid Resource APIs use opaque session credentials.\u003C/p\u003E\n\u003Cp\u003ECookie delivery is the default for incoming session credentials.\u003C/p\u003E\n\u003Cp\u003EThe Resource API validates the selected session through UAuthHub using the configured Hub address.\u003C/p\u003E\n\u003Cp\u003EThe browser must be able to send the session cookie to the Resource API.\u003C/p\u003E\n\u003Ch4 id=\u0022jwt-based-resource-apis\u0022\u003EJWT-based Resource APIs\u003C/h4\u003E\n\u003Cp\u003EPureJwt Resource APIs use JWT access tokens.\u003C/p\u003E\n\u003Cp\u003EThe default Blazor Resource Client attaches the current access token using:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EHTTP\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-http\u0022\u003EAuthorization: Bearer \u0026lt;access-token\u0026gt;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor a Resource API that exclusively uses header-based JWT authentication, browser cookies can be omitted:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Omit;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EOmitting browser cookies does not prevent the client from attaching its access-token authorization header.\u003C/p\u003E\n\u003Cp\u003EThis option affects Resource API requests, not authentication or refresh requests sent to UAuthHub.\u003C/p\u003E\n\u003Ch4 id=\u0022credential-compatibility\u0022\u003ECredential compatibility\u003C/h4\u003E\n\u003Cp\u003EA JWT issued in Hybrid mode is not interchangeable with a PureJwt access token.\u003C/p\u003E\n\u003Cp\u003EHybrid-aware JWT validation in separate Resource APIs is not currently implemented.\u003C/p\u003E\n\u003Cp\u003EAuthentication mode selection and credential compatibility remain explicit configuration responsibilities.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt-and-uauthhub-connectivity\u0022\u003EPureJwt and UAuthHub Connectivity\u003C/h3\u003E\n\u003Cp\u003EA PureJwt Resource API does not need to contact UAuthHub to validate each JWT.\u003C/p\u003E\n\u003Cp\u003EHowever, clients still use UAuthHub for login, refresh, and logout operations.\u003C/p\u003E\n\u003Cp\u003EThis separation allows protected APIs to validate access tokens independently while the authentication authority manages refresh-token state.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022device-and-application-profile-metadata\u0022\u003E8. Device and Application Profile Metadata\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth maintains a distinction between user identity, device identity, and client environment.\u003C/p\u003E\n\u003Cp\u003EFor browser resource requests, the transport can propagate UltimateAuth metadata, including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EX-UDID\nX-UAuth-ApplicationProfile\nX-Requested-With\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis keeps resource requests consistent with the UltimateAuth application environment without requiring every application component to construct these headers manually.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Edoes not require the developer to manually retrieve and attach the device identifier.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022metadata-is-not-proof-of-identity\u0022\u003EMetadata Is Not Proof of Identity\u003C/h3\u003E\n\u003Cp\u003EDevice identifiers and application profile values describe request context.\u003C/p\u003E\n\u003Cp\u003EThey are not independent authentication credentials.\u003C/p\u003E\n\u003Cp\u003EA receiving API must not grant access solely because a request declares a particular device identifier or application profile.\u003C/p\u003E\n\u003Cp\u003EThe server remains responsible for validating the user\u0027s authentication state and permissions.\u003C/p\u003E\n\u003Cp\u003EFor more information, see \u003Ca href=\u0022/docs/fundamentals/application-profiles\u0022\u003EApplication Profiles\u003C/a\u003E.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-transport-and-security\u0022\u003E9. Browser Transport and Security\u003C/h2\u003E\n\u003Cp\u003EThe Blazor Resource Client uses UltimateAuth\u0027s browser transport.\u003C/p\u003E\n\u003Cp\u003EThis allows UltimateAuth to apply consistent request behavior without requiring developers to write a separate JavaScript module for their application.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022origin-validation\u0022\u003EOrigin Validation\u003C/h3\u003E\n\u003Cp\u003EResource requests are constrained by the configured Resource API origin.\u003C/p\u003E\n\u003Cp\u003EThe transport validates request destinations rather than allowing arbitrary URLs to bypass the configured resource boundary.\u003C/p\u003E\n\u003Cp\u003EThis helps prevent application code from unintentionally sending credentials or UltimateAuth request metadata to unrelated destinations.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect-protection\u0022\u003ERedirect Protection\u003C/h3\u003E\n\u003Cp\u003EResource requests use redirect protection.\u003C/p\u003E\n\u003Cp\u003EA request should not silently follow a redirect to an unexpected destination while carrying authentication-related context.\u003C/p\u003E\n\u003Cp\u003EApplications should handle unexpected redirects as transport failures rather than assuming the request succeeded.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022request-cancellation\u0022\u003ERequest Cancellation\u003C/h3\u003E\n\u003Cp\u003EResource operations support \u003Ccode\u003ECancellationToken\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));\n\nvar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;, cts.Token);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Blazor transport coordinates cancellation with the underlying browser request.\u003C/p\u003E\n\u003Cp\u003ECancellation is particularly useful when a user navigates away from a page or starts another operation before the previous request completes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022browser-security-still-applies\u0022\u003EBrowser Security Still Applies\u003C/h3\u003E\n\u003Cp\u003EThe Resource Client does not disable browser security mechanisms.\u003C/p\u003E\n\u003Cp\u003ECross-origin requests remain subject to CORS and browser credential policies.\u003C/p\u003E\n\u003Cp\u003ELikewise, origin validation and redirect protection do not replace:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAuthentication validation.\u003C/li\u003E\n\u003Cli\u003EAuthorization policies.\u003C/li\u003E\n\u003Cli\u003ECSRF protection where applicable.\u003C/li\u003E\n\u003Cli\u003EInput validation.\u003C/li\u003E\n\u003Cli\u003EServer-side resource ownership checks.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese responsibilities remain part of the receiving API\u0027s security model.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server-vs.blazor-webassembly\u0022\u003E10. Blazor Server vs. Blazor WebAssembly\u003C/h2\u003E\n\u003Cp\u003EOne of UltimateAuth\u0027s design goals is to provide a consistent client API across supported application environments.\u003C/p\u003E\n\u003Cp\u003EHowever, different hosting models have different execution characteristics.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-webassembly\u0022\u003EBlazor WebAssembly\u003C/h3\u003E\n\u003Cp\u003EBlazor WebAssembly executes application code in the browser.\u003C/p\u003E\n\u003Cp\u003EIt cannot directly invoke server-side application services or access a server database.\u003C/p\u003E\n\u003Cp\u003EA typical application architecture is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor WebAssembly\n |\n v\nIUAuthClient.Resource\n |\n v\nResource API\n |\n v\nApplication Services\n |\n v\nDatabase\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client provides a natural way to access protected application data from this environment.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022blazor-server\u0022\u003EBlazor Server\u003C/h3\u003E\n\u003Cp\u003EBlazor Server executes component logic on the server.\u003C/p\u003E\n\u003Cp\u003EWhen the application service is available in the same process, a direct service call is often more appropriate.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EBlazor Server Component\n |\n v\nApplication Service\n |\n v\nDatabase\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar products = await productService.GetAllAsync();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThere is no requirement to introduce an HTTP request simply to use the Resource Client.\u003C/p\u003E\n\u003Cp\u003EHowever, when a Blazor Server application needs to communicate with a separate protected Resource API, it can use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Cstrong\u003EImportant:\u003C/strong\u003E The current Blazor Resource Client uses browser-based transport, including in Blazor Server applications.\u003C/p\u003E\n\u003Cp\u003EThe HTTP request is initiated by the user\u0027s browser, not by a server-side \u003Ccode\u003EHttpClient\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EFor server-to-server communication, use an appropriate server-side HTTP integration and authentication mechanism.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022the-same-client-api-different-application-architectures\u0022\u003EThe Same Client API, Different Application Architectures\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth aims to make client integration consistent without forcing every application into the same deployment model.\u003C/p\u003E\n\u003Cp\u003EThe goal is not to replace direct application service calls.\u003C/p\u003E\n\u003Cp\u003EThe goal is to remove unnecessary integration work whenever an HTTP resource request is actually needed.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-renewal-and-unauthorized-responses\u0022\u003E11. Authentication Renewal and Unauthorized Responses\u003C/h2\u003E\n\u003Cp\u003EThe Resource Client participates in UltimateAuth\u0027s coordinated authentication renewal infrastructure.\u003C/p\u003E\n\u003Cp\u003EWith proactive refresh enabled, an eligible request can renew authentication before being sent to the Resource API.\u003C/p\u003E\n\u003Cp\u003EWith reactive refresh enabled, a supported authentication challenge can trigger credential renewal and a single request replay.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\nif (result.IsSuccess)\n{\n products = result.Value;\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe application does not need to manually inspect token expiration or implement its own authentication retry loop.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022organizing-application-resource-services\u0022\u003E12. Organizing Application Resource Services\u003C/h2\u003E\n\u003Cp\u003EAlthough Resource Client operations can be called directly from components, larger applications often benefit from small, domain-specific services.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing CodeBeam.UltimateAuth.Client;\nusing CodeBeam.UltimateAuth.Core.Contracts;\n\npublic sealed class ProductApiService(IUAuthClient client)\n{\n public Task\u0026lt;UAuthResult\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;\u0026gt; GetAllAsync()\n =\u0026gt; client.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; GetAsync(int id)\n =\u0026gt; client.Resource.GetAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{id}\u0026quot;);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; CreateAsync(Product product)\n =\u0026gt; client.Resource.PostAsync\u0026lt;Product\u0026gt;(\u0026quot;/api/products\u0026quot;, product);\n\n public Task\u0026lt;UAuthResult\u0026lt;Product\u0026gt;\u0026gt; UpdateAsync(int id, Product product)\n =\u0026gt; client.Resource.PutAsync\u0026lt;Product\u0026gt;($\u0026quot;/api/products/{id}\u0026quot;, product);\n\n public Task\u0026lt;UAuthResult\u0026gt; DeleteAsync(int id)\n =\u0026gt; client.Resource.DeleteAsync($\u0026quot;/api/products/{id}\u0026quot;);\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis approach keeps application-specific endpoints and operations in one place.\u003C/p\u003E\n\u003Cp\u003EThe service does not need to implement:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA custom HTTP transport.\u003C/li\u003E\n\u003Cli\u003EBrowser credential handling.\u003C/li\u003E\n\u003Cli\u003EDevice metadata propagation.\u003C/li\u003E\n\u003Cli\u003EJSON response deserialization.\u003C/li\u003E\n\u003Cli\u003EA separate response wrapper.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThose responsibilities remain with UltimateAuth.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022keep-the-standard-result\u0022\u003EKeep the Standard Result\u003C/h3\u003E\n\u003Cp\u003ENotice that \u003Ccode\u003EProductApiService\u003C/code\u003E returns \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E directly.\u003C/p\u003E\n\u003Cp\u003EThere is no need to create another response type merely to wrap the same status, value, and problem information.\u003C/p\u003E\n\u003Cp\u003EThis keeps the application aligned with the UltimateAuth SDK.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-services-still-own-business-logic\u0022\u003EApplication Services Still Own Business Logic\u003C/h3\u003E\n\u003Cp\u003EThe Resource Client does not attempt to understand application-specific business rules.\u003C/p\u003E\n\u003Cp\u003EA \u003Ccode\u003EProductApiService\u003C/code\u003E can organize product-related operations, but the Resource API remains responsible for validating product data, enforcing ownership, and authorizing changes.\u003C/p\u003E\n\u003Cp\u003EThis separation keeps UltimateAuth focused on the infrastructure it can provide consistently.\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022design-philosophy\u0022\u003E13. Design Philosophy\u003C/h2\u003E\n\u003Cp\u003EThe Resource Client follows the same principle as the rest of UltimateAuth:\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EComplexity should be handled by the framework when it is common, predictable, and independent of application business logic.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EDevelopers should not need to repeatedly solve browser transport, credential configuration, device metadata, and response handling simply because their application has its own API.\u003C/p\u003E\n\u003Cp\u003EAt the same time, a framework should not hide important security boundaries or take ownership of application-specific decisions.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth therefore provides:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EA unified client entry point.\u003C/li\u003E\n\u003Cli\u003EFamiliar HTTP operations.\u003C/li\u003E\n\u003Cli\u003EConsistent result contracts.\u003C/li\u003E\n\u003Cli\u003EConfigurable resource origins and credential policies.\u003C/li\u003E\n\u003Cli\u003EBrowser-aware transport behavior.\u003C/li\u003E\n\u003Cli\u003EExplicit server-side security responsibilities.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe result is a simpler developer experience without requiring applications to abandon their existing architecture.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Authentication\nawait UAuthClient.Flows.RefreshAsync();\n\n// Identity\nvar user = await UAuthClient.Users.GetMeAsync();\n\n// Sessions\nvar sessions = await UAuthClient.Sessions.GetMyChainsAsync(\n new PageRequest\n {\n PageNumber = 1,\n PageSize = 10\n });\n\n// Application resources\nvar products = await UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent responsibilities. One consistent client model.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EUltimateAuth does not stop at authentication. It helps applications use authentication without rebuilding the integration layer around it.\u003C/strong\u003E\u003C/p\u003E\n\u003Chr\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022related-documentation\u0022\u003ERelated Documentation\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/overview\u0022\u003EClient SDK Overview\u003C/a\u003E \u2014 Understand the unified client architecture.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/client-options\u0022\u003EClient Options\u003C/a\u003E \u2014 Configure application profiles, authentication endpoints, and resource options.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/authentication\u0022\u003EAuthentication\u003C/a\u003E \u2014 Work with authentication flows and session renewal.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/application-profiles\u0022\u003EApplication Profiles\u003C/a\u003E \u2014 Understand runtime-specific authentication behavior.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/getting-started/real-world-setup\u0022\u003EReal-World Setup\u003C/a\u003E \u2014 Configure Blazor applications, UAuthHub, and separate Resource APIs.\u003C/li\u003E\n\u003C/ul\u003E\n", "Headings": [ { "Id": "the-problem-authentication-ends-integration-work-begins", @@ -194,15 +194,10 @@ "Level": 1 }, { - "Id": "handling-unauthorized-responses", - "Text": "11. Handling Unauthorized Responses", + "Id": "authentication-renewal-and-unauthorized-responses", + "Text": "11. Authentication Renewal and Unauthorized Responses", "Level": 0 }, - { - "Id": "automatic-refresh-and-retry", - "Text": "Automatic Refresh and Retry", - "Level": 1 - }, { "Id": "organizing-application-resource-services", "Text": "12. Organizing Application Resource Services", @@ -229,6 +224,6 @@ "Level": 0 } ], - "SourceHash": "E8CF8E1910155437F76F1463EAD34E2887C402EE836B582E4EA2834CE0AE5A30", + "SourceHash": "163613683B6C3AA5D48C2BB71792C02EF06EFFCDF432947C8C786058AB9FF71A", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/session-management.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/session-management.json index 1e95af80..02d23f67 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/session-management.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/session-management.json @@ -194,6 +194,6 @@ "Level": 0 } ], - "SourceHash": "BB7D06D3A3986BDE3FA6843804B51649FE7B3DE752C889A120F8AE68F3634308", + "SourceHash": "81F682CDEFDADA6DFE428F2385D488DBA62356B961B9832AFB175D82D6589DF5", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/user-management.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/user-management.json index be1ff7cb..16fa6e9f 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/user-management.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/client-sdk/user-management.json @@ -349,6 +349,6 @@ "Level": 0 } ], - "SourceHash": "708E3E8435E89EEFD4F930954942F143DF3DD0A16615190397ED7B722AD7239D", + "SourceHash": "631253C877264D0AB17C5C2EA5C2354981131568BB13FD0F5550C1553805D8A7", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/configuration/client-options.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/configuration/client-options.json index bcefd663..ceaf2fe6 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/configuration/client-options.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/configuration/client-options.json @@ -1,7 +1,7 @@ { "Slug": "configuration/client-options", "Title": "Client Options", - "Html": "\n\u003Cp\u003E\u003Ccode\u003EUAuthClientOptions\u003C/code\u003E controls how an UltimateAuth client communicates with the authentication server, executes authentication flows, maintains client-side authentication state, and responds when authentication must be renewed.\u003C/p\u003E\n\u003Cp\u003EThe client configuration is intentionally separate from server security configuration.\u003C/p\u003E\n\u003Cp\u003EThe server determines which authentication operations are permitted, how credentials are validated, and when sessions expire. The client determines how those operations are initiated and how the application responds to their outcomes.\u003C/p\u003E\n\u003Cp\u003EThis guide covers the current client configuration API, platform integration, defaults, practical examples, and important security considerations.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022register-the-ultimateauth-client\u0022\u003E1. Register the UltimateAuth Client\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth provides a platform-independent client SDK and platform-specific adapters.\u003C/p\u003E\n\u003Cp\u003EFor Blazor applications, use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EAddUltimateAuthClientBlazor()\u003C/code\u003E registers the underlying client services and the Blazor-specific infrastructure, including browser transport, storage, device identification, and authentication state integration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022core-client-registration\u0022\u003ECore Client Registration\u003C/h3\u003E\n\u003Cp\u003EThe platform-independent registration method is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClient(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis registers the shared client SDK.\u003C/p\u003E\n\u003Cp\u003EHowever, it does not provide every platform-specific implementation needed to run authentication flows.\u003C/p\u003E\n\u003Cp\u003EApplications should use an appropriate platform adapter rather than relying on the core client registration alone.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022do-not-register-both-client-methods\u0022\u003EDo Not Register Both Client Methods\u003C/h3\u003E\n\u003Cp\u003EWhen using:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Edo not also call:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClient();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Blazor registration already includes the core client services.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022server-and-client-in-one-application\u0022\u003EServer and Client in One Application\u003C/h3\u003E\n\u003Cp\u003EA Blazor Server application can register both UltimateAuth Server and the Blazor client adapter:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Session.Lifetime = TimeSpan.FromDays(7);\n});\n\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.AutoDetectApplicationProfile = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese registrations configure different components.\u003C/p\u003E\n\u003Cp\u003EThe server controls authentication security and lifecycle rules.\u003C/p\u003E\n\u003Cp\u003EThe client controls the application-side integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-architecture\u0022\u003E2. Client Options Architecture\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthClientOptions\u003C/code\u003E contains the following properties:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EType\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EIdentifies the application environment\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Ebool\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnables automatic profile detection\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDefault navigation destination after authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoints\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientEndpointOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication endpoint paths\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientLoginFlowOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin flow configuration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientPkceLoginFlowOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE flow configuration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientAutoRefreshOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBackground refresh coordination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientReauthOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientMultiTenantOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStateEvents\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthStateEventOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state event handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientResourceOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProtected Resource API origin and browser credential handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese options are configured through the same \u003Ccode\u003EUAuthClientOptions\u003C/code\u003E instance.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.Enabled = true;\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-profiles\u0022\u003E3. Application Profiles\u003C/h2\u003E\n\u003Cp\u003EThe application profile identifies the application environment and influences authentication flow behavior.\u003C/p\u003E\n\u003Cp\u003EConfigure it through:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.ApplicationProfile\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth defines profiles including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProfile\u003C/th\u003E\n\u003Cth\u003ETypical application\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBlazorServer\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInteractive Blazor Server applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBlazorWasm\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser-hosted Blazor WebAssembly\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMaui\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E.NET MAUI applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EWebServer\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETraditional ASP.NET Core web applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApi\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAPI-oriented clients\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthHub\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EUltimateAuth Hub\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENotSpecified\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProfile not explicitly selected\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent application profiles may result in different authentication modes on the server.\u003C/p\u003E\n\u003Cp\u003EFor example, the default server mode resolver maps Blazor Server to \u003Ccode\u003EPureOpaque\u003C/code\u003E and Blazor WebAssembly to \u003Ccode\u003EHybrid\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe application profile does not itself authorize an authentication mode. The server must support and permit the resolved mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-application-profile-detection\u0022\u003E4. Automatic Application Profile Detection\u003C/h2\u003E\n\u003Cp\u003EAutomatic profile detection is enabled by default:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoDetectApplicationProfile = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen enabled, UltimateAuth detects the application environment if \u003Ccode\u003EApplicationProfile\u003C/code\u003E remains \u003Ccode\u003ENotSpecified\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe current detector checks for:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EUAuthHub registration.\u003C/li\u003E\n\u003Cli\u003E.NET MAUI.\u003C/li\u003E\n\u003Cli\u003EBlazor WebAssembly.\u003C/li\u003E\n\u003Cli\u003EBlazor Server.\u003C/li\u003E\n\u003Cli\u003EA fallback to \u003Ccode\u003EWebServer\u003C/code\u003E.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022default-configuration\u0022\u003EDefault Configuration\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENo explicit profile is required for ordinary supported environments where detection succeeds.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-configuration\u0022\u003EManual Configuration\u003C/h3\u003E\n\u003Cp\u003EFor applications that need predictable behavior independent of assembly-based detection:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorWasm;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EManual configuration can be useful for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ESpecialized hosting environments.\u003C/li\u003E\n\u003Cli\u003EIntegration tests.\u003C/li\u003E\n\u003Cli\u003EApplications with multiple hosting models.\u003C/li\u003E\n\u003Cli\u003ECases where assembly-based detection is ambiguous.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022important-validation-rule\u0022\u003EImportant Validation Rule\u003C/h3\u003E\n\u003Cp\u003EThis configuration is invalid:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.NotSpecified;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen automatic detection is disabled, an explicit application profile must be provided.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022explicit-profiles-take-precedence\u0022\u003EExplicit Profiles Take Precedence\u003C/h3\u003E\n\u003Cp\u003EThe post-configuration detector does not replace a profile that has already been explicitly selected.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe explicit profile is retained even when automatic detection remains enabled.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022detection-limitations\u0022\u003EDetection Limitations\u003C/h3\u003E\n\u003Cp\u003EThe current detector uses service registration and loaded assemblies to identify the environment.\u003C/p\u003E\n\u003Cp\u003EAssembly-based detection may not be completely reliable in every hosting arrangement.\u003C/p\u003E\n\u003Cp\u003EFor complex Blazor Web App hosting scenarios, explicitly configuring the profile can make authentication behavior easier to reason about.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022endpoint-configuration\u0022\u003E5. Endpoint Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Endpoints\u003C/code\u003E defines the endpoint paths used by the client SDK.\u003C/p\u003E\n\u003Cp\u003EThe default base path is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E/auth\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-a-remote-authentication-server\u0022\u003EConfigure a Remote Authentication Server\u003C/h3\u003E\n\u003Cp\u003EFor a client communicating with a separately hosted UAuthHub:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor an application using same-origin authentication endpoints:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe base path must match the deployed authentication server\u0027s routing configuration.\u003C/p\u003E\n\u003Cp\u003EChanging a client endpoint does not create or expose the corresponding server endpoint.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022default-endpoint-paths\u0022\u003EDefault Endpoint Paths\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBasePath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/auth\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/login\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryLogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/try-login\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogout\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/logout\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefresh\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/refresh\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/reauth\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidate\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/validate\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceAuthorize\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/authorize\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceTryComplete\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/try-complete\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceComplete\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/complete\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubLoginPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/uauthhub/entry\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginTransport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/login/transport\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003EThe \u003Ccode\u003ELoginTransport\u003C/code\u003E endpoint exposes the effective login transport capabilities of the authentication server.\u003C/p\u003E\n\u003Cp\u003EThe client uses this information to determine whether navigation-based login is supported and whether the authentication response requires access-token processing.\u003C/p\u003E\n\u003Cp\u003EThis endpoint does not select an authentication mode or negotiate the server\u0027s authentication configuration.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022customize-individual-paths\u0022\u003ECustomize Individual Paths\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n options.Endpoints.Login = \u0026quot;/login\u0026quot;;\n options.Endpoints.Logout = \u0026quot;/logout\u0026quot;;\n options.Endpoints.Refresh = \u0026quot;/refresh\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese values should reflect the actual routes registered by UltimateAuth Server.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022required-endpoint-validation\u0022\u003ERequired Endpoint Validation\u003C/h3\u003E\n\u003Cp\u003EThe client options validator requires:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.BasePath\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Login\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Logout\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Refresh\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Validate\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese properties must not be null, empty, or whitespace-only.\u003C/p\u003E\n\u003Cp\u003EThe current validator does not apply the same required-value checks to every optional endpoint path.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022remote-clients-and-browser-security\u0022\u003ERemote Clients and Browser Security\u003C/h3\u003E\n\u003Cp\u003EWhen using a remote authentication server, also consider:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EHTTPS.\u003C/li\u003E\n\u003Cli\u003ECross-origin request configuration.\u003C/li\u003E\n\u003Cli\u003ECookie \u003Ccode\u003ESameSite\u003C/code\u003E and \u003Ccode\u003ESecure\u003C/code\u003E attributes.\u003C/li\u003E\n\u003Cli\u003EAllowed client origins.\u003C/li\u003E\n\u003Cli\u003EPKCE redirects.\u003C/li\u003E\n\u003Cli\u003EBrowser credential policies.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA correct endpoint URL alone does not guarantee that cross-origin authentication will work.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022resource-api-configuration\u0022\u003EResource API Configuration\u003C/h3\u003E\n\u003Cp\u003EAuthentication endpoints and application resource endpoints serve different purposes.\u003C/p\u003E\n\u003Cp\u003EAn application may authenticate through UAuthHub while retrieving business data from a separately deployed Resource API.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth provides \u003Ccode\u003Eoptions.Resource\u003C/code\u003E to configure these requests independently.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing CodeBeam.UltimateAuth.Client;\n\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client is available through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022resource-options\u0022\u003EResource Options\u003C/h4\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.BaseAddress\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EResource API origin; \u003Ccode\u003Enull\u003C/code\u003E uses the application\u0027s origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.Credentials\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser credential transmission policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022base-address-validation\u0022\u003EBase Address Validation\u003C/h4\u003E\n\u003Cp\u003EWhen configured, \u003Ccode\u003EResource.BaseAddress\u003C/code\u003E must be an absolute HTTP or HTTPS origin.\u003C/p\u003E\n\u003Cp\u003EHTTPS is required except for loopback development addresses.\u003C/p\u003E\n\u003Cp\u003EThe address must not contain an additional path, query string, fragment, or embedded credentials.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIndividual resource paths are supplied when making requests:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022credential-modes\u0022\u003ECredential Modes\u003C/h4\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthResourceCredentialsMode\u003C/code\u003E supports four options:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically select the appropriate browser credential policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESameOrigin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials only for same-origin requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInclude\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials for the configured Resource API origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not include browser credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EFor example, a separate Resource API that requires cross-origin cookies may use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Include;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource API must permit the relevant browser origin and support the required CORS and cookie configuration.\u003C/p\u003E\n\u003Cp\u003ECredential configuration does not bypass browser security restrictions or replace server-side authentication and authorization.\u003C/p\u003E\n\u003Ch4 id=\u0022resource-requests-and-authentication-lifecycle\u0022\u003EResource Requests and Authentication Lifecycle\u003C/h4\u003E\n\u003Cp\u003EResource requests use the browser transport in the Blazor integration.\u003C/p\u003E\n\u003Cp\u003EThey support request cancellation, origin validation, and redirect protection.\u003C/p\u003E\n\u003Cp\u003EResource requests return \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E or \u003Ccode\u003EUAuthResult\u003C/code\u003E, depending on the operation.\u003C/p\u003E\n\u003Cp\u003EThe current Resource Client does not automatically refresh authentication and retry a request after receiving a \u003Ccode\u003E401 Unauthorized\u003C/code\u003E response.\u003C/p\u003E\n\u003Cp\u003EFor a complete explanation, see \u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022login-flow-options\u0022\u003E6. Login Flow Options\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Login\u003C/code\u003E controls client-side login behavior.\u003C/p\u003E\n\u003Cp\u003EThe available properties are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin-specific return destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAllowCredentialPost\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAllow direct credential posting\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-login-navigation\u0022\u003EConfigure Login Navigation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe login-specific return URL is used when the login flow does not provide a more specific destination.\u003C/p\u003E\n\u003Cp\u003EIf it is not set, UltimateAuth can fall back to \u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E or the current location according to the flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-credential-posting\u0022\u003EDirect Credential Posting\u003C/h3\u003E\n\u003Cp\u003EThe default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is an important security setting.\u003C/p\u003E\n\u003Cp\u003EDirectly posting user credentials is not appropriate for public browser clients such as Blazor WebAssembly applications.\u003C/p\u003E\n\u003Cp\u003EPublic clients should use the supported PKCE-based login flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022trusted-server-hosted-clients\u0022\u003ETrusted Server-Hosted Clients\u003C/h3\u003E\n\u003Cp\u003EA trusted server-hosted application may explicitly enable direct credential posting where its authentication architecture requires it:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.Login.AllowCredentialPost = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDo not enable this setting for a public client merely to simplify login implementation.\u003C/p\u003E\n\u003Cp\u003EThe server still determines whether the requested authentication operation is permitted.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022pkce-configuration\u0022\u003E7. PKCE Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Pkce\u003C/code\u003E controls client-side PKCE login behavior.\u003C/p\u003E\n\u003Cp\u003EPKCE allows a public client to complete an authorization flow without relying on a confidential client secret.\u003C/p\u003E\n\u003Cp\u003EThe current options are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEnabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnable client PKCE support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPost-login return destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically navigate after beginning PKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnAuthorized\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECallback after the authorization response is issued\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022basic-configuration\u0022\u003EBasic Configuration\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.Enabled = true;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.AutoRedirect = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disable-automatic-redirect\u0022\u003EDisable Automatic Redirect\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.AutoRedirect = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen \u003Ccode\u003EAutoRedirect\u003C/code\u003E is disabled, \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E does not automatically navigate to the next location.\u003C/p\u003E\n\u003Cp\u003EThe application is responsible for handling navigation.\u003C/p\u003E\n\u003Cp\u003EThis can be useful when integrating UltimateAuth into an existing routing or navigation system.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authorization-callback\u0022\u003EAuthorization Callback\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.OnAuthorized = response =\u0026gt;\n {\n // Inspect or process the authorization response.\n return Task.CompletedTask;\n };\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback receives:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EPkceAuthorizeResponse\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIt runs after the authorization response is issued and before the normal Hub navigation.\u003C/p\u003E\n\u003Cp\u003EUse the callback for application-specific integration, not to bypass PKCE verification.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-and-server-pkce-settings-are-different\u0022\u003EClient and Server PKCE Settings Are Different\u003C/h3\u003E\n\u003Cp\u003EClient configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AutoRedirect = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EServer configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AuthorizationCodeLifetimeSeconds = 120;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client controls how the flow is initiated and navigated.\u003C/p\u003E\n\u003Cp\u003EThe server controls the authorization code\u0027s validity and verification.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022return-url-configuration\u0022\u003E8. Return URL Configuration\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports several return URL configuration points.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGlobal default for interactive authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin-specific default\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE-specific default\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022global-default\u0022\u003EGlobal Default\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022flow-specific-defaults\u0022\u003EFlow-Specific Defaults\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/account\u0026quot;;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFlow-specific values allow different authentication paths to use different destinations.\u003C/p\u003E\n\u003Cp\u003EAn explicitly supplied return URL for an individual operation may take precedence over these defaults.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-considerations\u0022\u003ESecurity Considerations\u003C/h3\u003E\n\u003Cp\u003EReturn URLs are navigation destinations and must be treated carefully.\u003C/p\u003E\n\u003Cp\u003EDo not redirect users to arbitrary external URLs without appropriate validation.\u003C/p\u003E\n\u003Cp\u003EOpen redirects can be abused for phishing and other attacks.\u003C/p\u003E\n\u003Cp\u003EPrefer local application routes unless cross-origin navigation is an intentional and validated part of the authentication architecture.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh\u0022\u003E9. Automatic Refresh\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.AutoRefresh\u003C/code\u003E controls background refresh coordination.\u003C/p\u003E\n\u003Cp\u003EThe available properties are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEnabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnables or disables automatic background refresh\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInterval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInterval between background refresh attempts\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-automatic-refresh\u0022\u003EConfigure Automatic Refresh\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Enabled = true;\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disable-automatic-refresh\u0022\u003EDisable Automatic Refresh\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Enabled = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022default-interval\u0022\u003EDefault Interval\u003C/h3\u003E\n\u003Cp\u003EIf \u003Ccode\u003EInterval\u003C/code\u003E is not supplied, the client registration applies:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoRefresh.Interval ??= TimeSpan.FromMinutes(5);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe resulting default interval is five minutes.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022platform-behavior\u0022\u003EPlatform Behavior\u003C/h3\u003E\n\u003Cp\u003EThe effective \u003Ccode\u003EEnabled\u003C/code\u003E setting should be considered together with the platform\u0027s post-configuration and session coordination behavior.\u003C/p\u003E\n\u003Cp\u003EThe current Blazor session coordinator checks \u003Ccode\u003EAutoRefresh.Enabled\u003C/code\u003E before starting its background loop.\u003C/p\u003E\n\u003Cp\u003EWhen enabled, it periodically invokes:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClient.Flows.RefreshAsync(true);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh-is-not-a-security-policy\u0022\u003EAutomatic Refresh Is Not a Security Policy\u003C/h3\u003E\n\u003Cp\u003EAutomatic refresh does not control:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EServer session lifetime.\u003C/li\u003E\n\u003Cli\u003ERefresh token lifetime.\u003C/li\u003E\n\u003Cli\u003ESession revocation.\u003C/li\u003E\n\u003Cli\u003ECredential recovery policies.\u003C/li\u003E\n\u003Cli\u003ERefresh token replay protection.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese remain server-side responsibilities.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh-does-not-guarantee-session-continuity\u0022\u003EAutomatic Refresh Does Not Guarantee Session Continuity\u003C/h3\u003E\n\u003Cp\u003EBackground refresh may fail because:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EThe session has expired.\u003C/li\u003E\n\u003Cli\u003EThe refresh credential has been revoked.\u003C/li\u003E\n\u003Cli\u003EThe browser is suspended.\u003C/li\u003E\n\u003Cli\u003ENetwork connectivity is unavailable.\u003C/li\u003E\n\u003Cli\u003EThe server requires reauthentication.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EAutomatic refresh is a convenience and continuity mechanism, not a guarantee that authentication remains valid indefinitely.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022coordinator-lifecycle\u0022\u003ECoordinator Lifecycle\u003C/h3\u003E\n\u003Cp\u003EThe Blazor adapter provides an \u003Ccode\u003EISessionCoordinator\u003C/code\u003E implementation.\u003C/p\u003E\n\u003Cp\u003EThe coordinator must be started by the application\u0027s supported initialization lifecycle.\u003C/p\u003E\n\u003Cp\u003ESetting \u003Ccode\u003EAutoRefresh.Enabled = true\u003C/code\u003E does not mean that a background task automatically runs without the coordinator being started.\u003C/p\u003E\n\u003Cp\u003EApplications should follow the client initialization guidance for their hosting model.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022reauthentication-options\u0022\u003E10. Reauthentication Options\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Reauth\u003C/code\u003E controls how the Blazor session coordinator responds when refresh reports that reauthentication is required.\u003C/p\u003E\n\u003Cp\u003EThe available properties are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBehavior\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthBehavior.Redirect\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERedirectPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-behaviors\u0022\u003EAvailable Behaviors\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EReauthBehavior.Redirect\nReauthBehavior.None\nReauthBehavior.RaiseEvent\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect\u0022\u003ERedirect\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the coordinator receives a \u003Ccode\u003EReauthRequired\u003C/code\u003E refresh outcome, it navigates to the configured redirect path.\u003C/p\u003E\n\u003Cp\u003EIf \u003Ccode\u003ERedirectPath\u003C/code\u003E is null, the coordinator falls back to \u003Ccode\u003EEndpoints.Login\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe current Blazor coordinator uses forced navigation for this redirect.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022raise-an-event\u0022\u003ERaise an Event\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.RaiseEvent;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis allows an application to handle reauthentication through the coordinator\u0027s \u003Ccode\u003EReauthRequired\u003C/code\u003E event.\u003C/p\u003E\n\u003Cp\u003EFor example, an application may display a reauthentication dialog rather than immediately navigating.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022no-automatic-action\u0022\u003ENo Automatic Action\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.None;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith \u003Ccode\u003ENone\u003C/code\u003E, the coordinator does not automatically redirect or raise its reauthentication event.\u003C/p\u003E\n\u003Cp\u003EThe application must still handle unauthenticated states appropriately.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022important\u0022\u003EImportant\u003C/h3\u003E\n\u003Cp\u003EReauthentication behavior does not make an expired or revoked session valid.\u003C/p\u003E\n\u003Cp\u003EIt only controls how the client responds when authentication must be reestablished.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022multi-tenant-client-configuration\u0022\u003E11. Multi-Tenant Client Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.MultiTenant\u003C/code\u003E controls tenant propagation from the client to the authentication server.\u003C/p\u003E\n\u003Cp\u003EThe client does not independently authorize or resolve tenant ownership.\u003C/p\u003E\n\u003Cp\u003EIt carries tenant context using the configured transport.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-properties\u0022\u003EAvailable Properties\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEnabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnable tenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant identifier to propagate\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETransport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ETenantTransport.None\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant transport mechanism\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-transports\u0022\u003EAvailable Transports\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003ETenantTransport.None\nTenantTransport.Header\nTenantTransport.Route\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022header-based-tenant-propagation\u0022\u003EHeader-Based Tenant Propagation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.Tenant = \u0026quot;tenant-a\u0026quot;;\n options.MultiTenant.Transport = TenantTransport.Header;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe server must be configured to resolve tenant information from the corresponding transport.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.EnableHeader = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022route-based-tenant-propagation\u0022\u003ERoute-Based Tenant Propagation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.Tenant = \u0026quot;tenant-a\u0026quot;;\n options.MultiTenant.Transport = TenantTransport.Route;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe server must expose routes compatible with tenant-based routing.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-boundary\u0022\u003ESecurity Boundary\u003C/h3\u003E\n\u003Cp\u003EA client-provided tenant identifier is not proof of tenant membership.\u003C/p\u003E\n\u003Cp\u003EThe server must validate the resolved tenant and enforce tenant isolation.\u003C/p\u003E\n\u003Cp\u003ENever rely on client-side tenant selection as an authorization boundary.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-state-events\u0022\u003E12. Authentication State Events\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.StateEvents\u003C/code\u003E controls how the client processes authentication-related state events.\u003C/p\u003E\n\u003Cp\u003EThe available property is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.StateEvents.HandlingMode\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIts default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthStateEventHandlingMode.Patch\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-modes\u0022\u003EAvailable Modes\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApply a local authentication state update\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidate\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevalidate authentication state after the event\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not update authentication state in response to the event\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022patch\u0022\u003EPatch\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EPatch\u003C/code\u003E is the default.\u003C/p\u003E\n\u003Cp\u003EIt allows the client to update local state without performing a full authentication validation for every event.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validate\u0022\u003EValidate\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Validate;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EValidate\u003C/code\u003E causes the client to revalidate authentication state in response to events.\u003C/p\u003E\n\u003Cp\u003EThis may introduce additional requests but can be appropriate when the application prefers server-confirmed state updates.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022none\u0022\u003ENone\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.None;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ENone\u003C/code\u003E disables automatic authentication state updates in response to these events.\u003C/p\u003E\n\u003Cp\u003EApplications using this mode must provide any required state synchronization through other mechanisms.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022local-events-are-not-distributed-notifications\u0022\u003ELocal Events Are Not Distributed Notifications\u003C/h3\u003E\n\u003Cp\u003EClient state events do not automatically notify every browser, device, or application instance.\u003C/p\u003E\n\u003Cp\u003EFor example, an administrator changing a user\u0027s role does not automatically push an event to that user\u0027s open browser.\u003C/p\u003E\n\u003Cp\u003EDistributed synchronization requires additional application infrastructure.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuration-from-appsettings.json\u0022\u003E13. Configuration from appsettings.json\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth Client binds the configuration section:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth:Client\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EJSON\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-json\u0022\u003E{\n \u0026quot;UltimateAuth\u0026quot;: {\n \u0026quot;Client\u0026quot;: {\n \u0026quot;AutoDetectApplicationProfile\u0026quot;: true,\n \u0026quot;DefaultReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;,\n \u0026quot;Endpoints\u0026quot;: {\n \u0026quot;BasePath\u0026quot;: \u0026quot;https://auth.example.com/auth\u0026quot;\n },\n \u0026quot;Pkce\u0026quot;: {\n \u0026quot;Enabled\u0026quot;: true,\n \u0026quot;ReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;,\n \u0026quot;AutoRedirect\u0026quot;: true\n },\n \u0026quot;AutoRefresh\u0026quot;: {\n \u0026quot;Enabled\u0026quot;: true,\n \u0026quot;Interval\u0026quot;: \u0026quot;00:05:00\u0026quot;\n },\n \u0026quot;Reauth\u0026quot;: {\n \u0026quot;Behavior\u0026quot;: \u0026quot;Redirect\u0026quot;,\n \u0026quot;RedirectPath\u0026quot;: \u0026quot;/login\u0026quot;\n },\n \u0026quot;StateEvents\u0026quot;: {\n \u0026quot;HandlingMode\u0026quot;: \u0026quot;Patch\u0026quot;\n }\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe example uses the standard ASP.NET Core configuration binding conventions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuration-precedence\u0022\u003EConfiguration Precedence\u003C/h3\u003E\n\u003Cp\u003EThe registration pipeline applies:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EOption type defaults.\u003C/li\u003E\n\u003Cli\u003EThe configuration delegate.\u003C/li\u003E\n\u003Cli\u003EValues from \u003Ccode\u003EUltimateAuth:Client\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EPost-configuration processing.\u003C/li\u003E\n\u003Cli\u003ERegistered options validation when the options are resolved.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EJSON\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-json\u0022\u003E{\n \u0026quot;UltimateAuth\u0026quot;: {\n \u0026quot;Client\u0026quot;: {\n \u0026quot;DefaultReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe configured return URL becomes \u003Ccode\u003E/dashboard\u003C/code\u003E.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022environment-variables\u0022\u003EEnvironment Variables\u003C/h3\u003E\n\u003Cp\u003EASP.NET Core supports double underscores for hierarchical configuration keys.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth__Client__Endpoints__BasePath=https://auth.example.com/auth\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis corresponds to:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth:Client:Endpoints:BasePath\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUse environment-specific configuration for deployment-dependent values such as authentication server addresses and application return paths.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-validation\u0022\u003E14. Client Options Validation\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth registers validators for:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClientOptions\nUAuthClientEndpointOptions\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-profile-validation\u0022\u003EApplication Profile Validation\u003C/h3\u003E\n\u003Cp\u003EThe validator rejects a configuration where:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoDetectApplicationProfile = false;\noptions.ApplicationProfile = UAuthApplicationProfile.NotSpecified;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAn explicit profile is required when detection is disabled.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022endpoint-validation\u0022\u003EEndpoint Validation\u003C/h3\u003E\n\u003Cp\u003EThe following endpoint properties must be present:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EEndpoints.BasePath\nEndpoints.Login\nEndpoints.Logout\nEndpoints.Refresh\nEndpoints.Validate\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example, this configuration is invalid:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validation-timing\u0022\u003EValidation Timing\u003C/h3\u003E\n\u003Cp\u003EUnlike the server registration, the current client registration does not explicitly call \u003Ccode\u003EValidateOnStart()\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EValidation therefore occurs through the normal options resolution lifecycle.\u003C/p\u003E\n\u003Cp\u003EApplications that require early validation can arrange for the configured options to be resolved during startup.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validation-scope\u0022\u003EValidation Scope\u003C/h3\u003E\n\u003Cp\u003EThe current validators check essential application profile and endpoint requirements.\u003C/p\u003E\n\u003Cp\u003EThey do not automatically validate every possible combination of client flow, server deployment, cookie behavior, and authentication mode.\u003C/p\u003E\n\u003Cp\u003EApplications should test their actual authentication flows against the deployed server configuration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-blazor-webassembly-example\u0022\u003E15. Complete Blazor WebAssembly Example\u003C/h2\u003E\n\u003Cp\u003EThe following example configures a Blazor WebAssembly client using a remote authentication server.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n // Application profile\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorWasm;\n\n // Authentication server\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n // Navigation\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\n // Public client security\n options.Login.AllowCredentialPost = false;\n\n // PKCE\n options.Pkce.Enabled = true;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.AutoRedirect = true;\n\n // Background refresh\n options.AutoRefresh.Enabled = false;\n\n // Reauthentication\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n\n // State updates\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis example emphasizes PKCE-based authentication and avoids direct credential posting from a public browser client.\u003C/p\u003E\n\u003Cp\u003EThe remote server must be configured with compatible endpoints, origins, authentication modes, and credential delivery policies.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-blazor-server-example\u0022\u003E16. Complete Blazor Server Example\u003C/h2\u003E\n\u003Cp\u003EThe following example configures a Blazor Server client.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n // Application profile\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n\n // Same-origin authentication endpoints\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n\n // Navigation\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\n // Background refresh\n options.AutoRefresh.Enabled = true;\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n\n // Reauthentication\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n\n // Authentication state\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EBlazor Server applications can use session-oriented authentication and the corresponding server-side security policies.\u003C/p\u003E\n\u003Cp\u003EThe application must still initialize the client and session coordinator through its supported lifecycle.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022server-and-client-configuration-together\u0022\u003E17. Server and Client Configuration Together\u003C/h2\u003E\n\u003Cp\u003EAn application that hosts both UltimateAuth Server and the Blazor client adapter can configure them independently.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Server: authentication and security policies\nbuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.AllowedModes =\n [\n UAuthMode.PureOpaque,\n UAuthMode.Hybrid\n ];\n\n options.Session.Lifetime = TimeSpan.FromDays(7);\n options.Login.MaxFailedAttempts = 5;\n});\n\n// Client: platform integration and flow behavior\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.AutoDetectApplicationProfile = false;\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n options.AutoRefresh.Enabled = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe two configuration objects have different responsibilities.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ERequirement\u003C/th\u003E\n\u003Cth\u003EConfigure on\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESession lifetime\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAccess token lifetime\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ERefresh token replay policy\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ECredential recovery rules\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAllowed authentication modes\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EApplication profile\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPKCE navigation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAutomatic background refresh\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EReauthentication navigation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAuthentication state event handling\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ETenant validation\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe client cannot override server-side security decisions.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022common-configuration-mistakes\u0022\u003E18. Common Configuration Mistakes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022registering-the-core-client-and-blazor-adapter-separately\u0022\u003ERegistering the Core Client and Blazor Adapter Separately\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003EAddUltimateAuthClientBlazor()\u003C/code\u003E for Blazor applications.\u003C/p\u003E\n\u003Cp\u003EIt already registers the underlying client SDK.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disabling-profile-detection-without-selecting-a-profile\u0022\u003EDisabling Profile Detection Without Selecting a Profile\u003C/h3\u003E\n\u003Cp\u003EWhen \u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E is false, set \u003Ccode\u003EApplicationProfile\u003C/code\u003E explicitly.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022relying-on-automatic-detection-in-an-ambiguous-hosting-environment\u0022\u003ERelying on Automatic Detection in an Ambiguous Hosting Environment\u003C/h3\u003E\n\u003Cp\u003EFor complex hosting arrangements, consider specifying the application profile explicitly.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022enabling-direct-credential-posting-in-a-public-client\u0022\u003EEnabling Direct Credential Posting in a Public Client\u003C/h3\u003E\n\u003Cp\u003EDo not enable \u003Ccode\u003EAllowCredentialPost\u003C/code\u003E for browser-hosted public clients.\u003C/p\u003E\n\u003Cp\u003EUse PKCE.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-client-auto-refresh-extends-server-lifetimes\u0022\u003EAssuming Client Auto-Refresh Extends Server Lifetimes\u003C/h3\u003E\n\u003Cp\u003EAutomatic refresh only initiates refresh operations.\u003C/p\u003E\n\u003Cp\u003EThe server controls whether refresh is permitted.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-auto-refresh-starts-automatically\u0022\u003EAssuming Auto-Refresh Starts Automatically\u003C/h3\u003E\n\u003Cp\u003EThe Blazor session coordinator must be started through the supported application lifecycle.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuring-only-the-client-endpoint\u0022\u003EConfiguring Only the Client Endpoint\u003C/h3\u003E\n\u003Cp\u003EThe server must expose compatible routes and allow the intended cross-origin interaction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022treating-tenant-propagation-as-authorization\u0022\u003ETreating Tenant Propagation as Authorization\u003C/h3\u003E\n\u003Cp\u003EA tenant identifier supplied by the client does not grant access to that tenant.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-state-events-as-distributed-notifications\u0022\u003EUsing State Events as Distributed Notifications\u003C/h3\u003E\n\u003Cp\u003EClient events update local client state; they do not automatically synchronize all connected devices.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-every-client-setting-is-validated-at-startup\u0022\u003EAssuming Every Client Setting Is Validated at Startup\u003C/h3\u003E\n\u003Cp\u003EThe current client registration validates options when they are resolved, rather than explicitly requiring startup validation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-quick-reference\u0022\u003E19. Client Options Quick Reference\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOption\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ENotSpecified\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApplication environment\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatic profile detection\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGlobal return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoints.BasePath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/auth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication endpoint base\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.AllowCredentialPost\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDirect credential posting\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.Enabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE flow support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.AutoRedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatic PKCE navigation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.OnAuthorized\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE authorization callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Interval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E5 minutes after post-configuration\u003C/td\u003E\n\u003Ctd\u003EBackground refresh interval\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth.Behavior\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ERedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth.RedirectPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication redirect\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Enabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Tenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Transport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant transport\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStateEvents.HandlingMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EState event handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.BaseAddress\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EResource API origin; defaults to application origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.Credentials\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser credential handling for resource requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EAutoRefresh.Enabled\u003C/code\u003E should be evaluated with the applicable platform and post-configuration behavior rather than inferred solely from its property initializer.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003EConfiguration Overview\u003C/strong\u003E \u2014 Understand the configuration architecture and source precedence.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EServer Options\u003C/strong\u003E \u2014 Configure authentication security, sessions, tokens, and endpoints.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EAdvanced Configuration\u003C/strong\u003E \u2014 Explore effective options, mode resolution, and extension points.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EClient Authentication\u003C/strong\u003E \u2014 Implement login, PKCE, refresh, and logout flows.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EClient Session Management\u003C/strong\u003E \u2014 Manage authenticated sessions and revocation.\u003C/li\u003E\n\u003C/ul\u003E\n", + "Html": "\n\u003Cp\u003E\u003Ccode\u003EUAuthClientOptions\u003C/code\u003E controls how an UltimateAuth client communicates with the authentication server, executes authentication flows, maintains client-side authentication state, and responds when authentication must be renewed.\u003C/p\u003E\n\u003Cp\u003EThe client configuration is intentionally separate from server security configuration.\u003C/p\u003E\n\u003Cp\u003EThe server determines which authentication operations are permitted, how credentials are validated, and when sessions expire. The client determines how those operations are initiated and how the application responds to their outcomes.\u003C/p\u003E\n\u003Cp\u003EThis guide covers the current client configuration API, platform integration, defaults, practical examples, and important security considerations.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022register-the-ultimateauth-client\u0022\u003E1. Register the UltimateAuth Client\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth provides a platform-independent client SDK and platform-specific adapters.\u003C/p\u003E\n\u003Cp\u003EFor Blazor applications, use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EAddUltimateAuthClientBlazor()\u003C/code\u003E registers the underlying client services and the Blazor-specific infrastructure, including browser transport, storage, device identification, and authentication state integration.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022core-client-registration\u0022\u003ECore Client Registration\u003C/h3\u003E\n\u003Cp\u003EThe platform-independent registration method is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClient(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis registers the shared client SDK.\u003C/p\u003E\n\u003Cp\u003EHowever, it does not provide every platform-specific implementation needed to run authentication flows.\u003C/p\u003E\n\u003Cp\u003EApplications should use an appropriate platform adapter rather than relying on the core client registration alone.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022do-not-register-both-client-methods\u0022\u003EDo Not Register Both Client Methods\u003C/h3\u003E\n\u003Cp\u003EWhen using:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003Edo not also call:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClient();\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Blazor registration already includes the core client services.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022server-and-client-in-one-application\u0022\u003EServer and Client in One Application\u003C/h3\u003E\n\u003Cp\u003EA Blazor Server application can register both UltimateAuth Server and the Blazor client adapter:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.Session.Lifetime = TimeSpan.FromDays(7);\n});\n\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.AutoDetectApplicationProfile = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese registrations configure different components.\u003C/p\u003E\n\u003Cp\u003EThe server controls authentication security and lifecycle rules.\u003C/p\u003E\n\u003Cp\u003EThe client controls the application-side integration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-architecture\u0022\u003E2. Client Options Architecture\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthClientOptions\u003C/code\u003E contains the following properties:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EType\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EIdentifies the application environment\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Ebool\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnables automatic profile detection\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Estring?\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDefault navigation destination after authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoints\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientEndpointOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication endpoint paths\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientLoginFlowOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin flow configuration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientPkceLoginFlowOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE flow configuration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientAutoRefreshOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProactive, reactive, and background refresh coordination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientReauthOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication behavior\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientMultiTenantOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStateEvents\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthStateEventOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state event handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthClientResourceOptions\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProtected Resource API origin and browser credential handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese options are configured through the same \u003Ccode\u003EUAuthClientOptions\u003C/code\u003E instance.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.Enabled = true;\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-profiles\u0022\u003E3. Application Profiles\u003C/h2\u003E\n\u003Cp\u003EThe application profile identifies the application environment and influences authentication flow behavior.\u003C/p\u003E\n\u003Cp\u003EConfigure it through:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.ApplicationProfile\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUltimateAuth defines profiles including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProfile\u003C/th\u003E\n\u003Cth\u003ETypical application\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBlazorServer\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInteractive Blazor Server applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBlazorWasm\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser-hosted Blazor WebAssembly\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMaui\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E.NET MAUI applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EWebServer\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETraditional ASP.NET Core web applications\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApi\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAPI-oriented clients\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EUAuthHub\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EUltimateAuth Hub\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENotSpecified\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EProfile not explicitly selected\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EDifferent application profiles may result in different authentication modes on the server.\u003C/p\u003E\n\u003Cp\u003EFor example, the default server mode resolver maps Blazor Server to \u003Ccode\u003EPureOpaque\u003C/code\u003E and Blazor WebAssembly to \u003Ccode\u003EHybrid\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe application profile does not itself authorize an authentication mode. The server must support and permit the resolved mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-application-profile-detection\u0022\u003E4. Automatic Application Profile Detection\u003C/h2\u003E\n\u003Cp\u003EAutomatic profile detection is enabled by default:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoDetectApplicationProfile = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen enabled, UltimateAuth detects the application environment if \u003Ccode\u003EApplicationProfile\u003C/code\u003E remains \u003Ccode\u003ENotSpecified\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe current detector checks for:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EUAuthHub registration.\u003C/li\u003E\n\u003Cli\u003E.NET MAUI.\u003C/li\u003E\n\u003Cli\u003EBlazor WebAssembly.\u003C/li\u003E\n\u003Cli\u003EBlazor Server.\u003C/li\u003E\n\u003Cli\u003EA fallback to \u003Ccode\u003EWebServer\u003C/code\u003E.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022default-configuration\u0022\u003EDefault Configuration\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003ENo explicit profile is required for ordinary supported environments where detection succeeds.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022manual-configuration\u0022\u003EManual Configuration\u003C/h3\u003E\n\u003Cp\u003EFor applications that need predictable behavior independent of assembly-based detection:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorWasm;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EManual configuration can be useful for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ESpecialized hosting environments.\u003C/li\u003E\n\u003Cli\u003EIntegration tests.\u003C/li\u003E\n\u003Cli\u003EApplications with multiple hosting models.\u003C/li\u003E\n\u003Cli\u003ECases where assembly-based detection is ambiguous.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022important-validation-rule\u0022\u003EImportant Validation Rule\u003C/h3\u003E\n\u003Cp\u003EThis configuration is invalid:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.NotSpecified;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen automatic detection is disabled, an explicit application profile must be provided.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022explicit-profiles-take-precedence\u0022\u003EExplicit Profiles Take Precedence\u003C/h3\u003E\n\u003Cp\u003EThe post-configuration detector does not replace a profile that has already been explicitly selected.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe explicit profile is retained even when automatic detection remains enabled.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022detection-limitations\u0022\u003EDetection Limitations\u003C/h3\u003E\n\u003Cp\u003EThe current detector uses service registration and loaded assemblies to identify the environment.\u003C/p\u003E\n\u003Cp\u003EAssembly-based detection may not be completely reliable in every hosting arrangement.\u003C/p\u003E\n\u003Cp\u003EFor complex Blazor Web App hosting scenarios, explicitly configuring the profile can make authentication behavior easier to reason about.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022endpoint-configuration\u0022\u003E5. Endpoint Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Endpoints\u003C/code\u003E defines the endpoint paths used by the client SDK.\u003C/p\u003E\n\u003Cp\u003EThe default base path is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003E/auth\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-a-remote-authentication-server\u0022\u003EConfigure a Remote Authentication Server\u003C/h3\u003E\n\u003Cp\u003EFor a client communicating with a separately hosted UAuthHub:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor an application using same-origin authentication endpoints:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe base path must match the deployed authentication server\u0027s routing configuration.\u003C/p\u003E\n\u003Cp\u003EChanging a client endpoint does not create or expose the corresponding server endpoint.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022default-endpoint-paths\u0022\u003EDefault Endpoint Paths\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBasePath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/auth\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/login\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETryLogin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/try-login\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogout\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/logout\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefresh\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/refresh\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/reauth\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidate\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/validate\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceAuthorize\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/authorize\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceTryComplete\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/try-complete\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkceComplete\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/pkce/complete\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EHubLoginPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/uauthhub/entry\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELoginTransport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/login/transport\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cblockquote\u003E\n\u003Cp\u003EThe \u003Ccode\u003ELoginTransport\u003C/code\u003E endpoint exposes the effective login transport capabilities of the authentication server.\u003C/p\u003E\n\u003Cp\u003EThe client uses this information to determine whether navigation-based login is supported and whether the authentication response requires access-token processing.\u003C/p\u003E\n\u003Cp\u003EThis endpoint does not select an authentication mode or negotiate the server\u0027s authentication configuration.\u003C/p\u003E\n\u003C/blockquote\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022customize-individual-paths\u0022\u003ECustomize Individual Paths\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n options.Endpoints.Login = \u0026quot;/login\u0026quot;;\n options.Endpoints.Logout = \u0026quot;/logout\u0026quot;;\n options.Endpoints.Refresh = \u0026quot;/refresh\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThese values should reflect the actual routes registered by UltimateAuth Server.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022required-endpoint-validation\u0022\u003ERequired Endpoint Validation\u003C/h3\u003E\n\u003Cp\u003EThe client options validator requires:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.BasePath\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Login\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Logout\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Refresh\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003EEndpoints.Validate\u003C/code\u003E\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThese properties must not be null, empty, or whitespace-only.\u003C/p\u003E\n\u003Cp\u003EThe current validator does not apply the same required-value checks to every optional endpoint path.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022remote-clients-and-browser-security\u0022\u003ERemote Clients and Browser Security\u003C/h3\u003E\n\u003Cp\u003EWhen using a remote authentication server, also consider:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EHTTPS.\u003C/li\u003E\n\u003Cli\u003ECross-origin request configuration.\u003C/li\u003E\n\u003Cli\u003ECookie \u003Ccode\u003ESameSite\u003C/code\u003E and \u003Ccode\u003ESecure\u003C/code\u003E attributes.\u003C/li\u003E\n\u003Cli\u003EAllowed client origins.\u003C/li\u003E\n\u003Cli\u003EPKCE redirects.\u003C/li\u003E\n\u003Cli\u003EBrowser credential policies.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA correct endpoint URL alone does not guarantee that cross-origin authentication will work.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022resource-api-configuration\u0022\u003EResource API Configuration\u003C/h3\u003E\n\u003Cp\u003EAuthentication endpoints and application resource endpoints serve different purposes.\u003C/p\u003E\n\u003Cp\u003EAn application may authenticate through UAuthHub while retrieving business data from a separately deployed Resource API.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth provides \u003Ccode\u003Eoptions.Resource\u003C/code\u003E to configure these requests independently.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eusing CodeBeam.UltimateAuth.Client;\n\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n options.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource Client is available through \u003Ccode\u003EIUAuthClient.Resource\u003C/code\u003E.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Evar result = await UAuthClient.Resource\n .GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022resource-options\u0022\u003EResource Options\u003C/h4\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.BaseAddress\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EResource API origin; \u003Ccode\u003Enull\u003C/code\u003E uses the application\u0027s origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.Credentials\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser credential transmission policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022base-address-validation\u0022\u003EBase Address Validation\u003C/h4\u003E\n\u003Cp\u003EWhen configured, \u003Ccode\u003EResource.BaseAddress\u003C/code\u003E must be an absolute HTTP or HTTPS origin.\u003C/p\u003E\n\u003Cp\u003EHTTPS is required except for loopback development addresses.\u003C/p\u003E\n\u003Cp\u003EThe address must not contain an additional path, query string, fragment, or embedded credentials.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.BaseAddress = \u0026quot;https://api.example.com\u0026quot;;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIndividual resource paths are supplied when making requests:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eawait UAuthClient.Resource.GetAsync\u0026lt;List\u0026lt;Product\u0026gt;\u0026gt;(\u0026quot;/api/products\u0026quot;);\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch4 id=\u0022credential-modes\u0022\u003ECredential Modes\u003C/h4\u003E\n\u003Cp\u003E\u003Ccode\u003EUAuthResourceCredentialsMode\u003C/code\u003E supports four options:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically select the appropriate browser credential policy\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ESameOrigin\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials only for same-origin requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInclude\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EInclude browser credentials for the configured Resource API origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOmit\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not include browser credentials\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EFor example, a separate Resource API that requires cross-origin cookies may use:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Resource.Credentials = UAuthResourceCredentialsMode.Include;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe Resource API must permit the relevant browser origin and support the required CORS and cookie configuration.\u003C/p\u003E\n\u003Cp\u003ECredential configuration does not bypass browser security restrictions or replace server-side authentication and authorization.\u003C/p\u003E\n\u003Ch4 id=\u0022resource-requests-and-authentication-lifecycle\u0022\u003EResource Requests and Authentication Lifecycle\u003C/h4\u003E\n\u003Cp\u003EResource requests use the browser transport in the Blazor integration.\u003C/p\u003E\n\u003Cp\u003EThey support request cancellation, origin validation, and redirect protection.\u003C/p\u003E\n\u003Cp\u003EResource requests return \u003Ccode\u003EUAuthResult\u0026lt;T\u0026gt;\u003C/code\u003E or \u003Ccode\u003EUAuthResult\u003C/code\u003E, depending on the operation.\u003C/p\u003E\n\u003Cp\u003EThe current Resource Client does not automatically refresh authentication and retry a request after receiving a \u003Ccode\u003E401 Unauthorized\u003C/code\u003E response.\u003C/p\u003E\n\u003Cp\u003EFor a complete explanation, see \u003Ca href=\u0022/docs/client-sdk/resource-api-requests\u0022\u003EResource API Requests\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022login-flow-options\u0022\u003E6. Login Flow Options\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Login\u003C/code\u003E controls client-side login behavior.\u003C/p\u003E\n\u003Cp\u003EThe available properties are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin-specific return destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAllowCredentialPost\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAllow direct credential posting\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configure-login-navigation\u0022\u003EConfigure Login Navigation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe login-specific return URL is used when the login flow does not provide a more specific destination.\u003C/p\u003E\n\u003Cp\u003EIf it is not set, UltimateAuth can fall back to \u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E or the current location according to the flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022direct-credential-posting\u0022\u003EDirect Credential Posting\u003C/h3\u003E\n\u003Cp\u003EThe default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Login.AllowCredentialPost = false;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is an important security setting.\u003C/p\u003E\n\u003Cp\u003EDirectly posting user credentials is not appropriate for public browser clients such as Blazor WebAssembly applications.\u003C/p\u003E\n\u003Cp\u003EPublic clients should use the supported PKCE-based login flow.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022trusted-server-hosted-clients\u0022\u003ETrusted Server-Hosted Clients\u003C/h3\u003E\n\u003Cp\u003EA trusted server-hosted application may explicitly enable direct credential posting where its authentication architecture requires it:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.Login.AllowCredentialPost = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EDo not enable this setting for a public client merely to simplify login implementation.\u003C/p\u003E\n\u003Cp\u003EThe server still determines whether the requested authentication operation is permitted.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022pkce-configuration\u0022\u003E7. PKCE Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Pkce\u003C/code\u003E controls client-side PKCE login behavior.\u003C/p\u003E\n\u003Cp\u003EPKCE allows a public client to complete an authorization flow without relying on a confidential client secret.\u003C/p\u003E\n\u003Cp\u003EThe current options are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEnabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnable client PKCE support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPost-login return destination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatically navigate after beginning PKCE\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EOnAuthorized\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ECallback after the authorization response is issued\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022basic-configuration\u0022\u003EBasic Configuration\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.Enabled = true;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.AutoRedirect = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disable-automatic-redirect\u0022\u003EDisable Automatic Redirect\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.AutoRedirect = false;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen \u003Ccode\u003EAutoRedirect\u003C/code\u003E is disabled, \u003Ccode\u003EBeginPkceAsync\u003C/code\u003E does not automatically navigate to the next location.\u003C/p\u003E\n\u003Cp\u003EThe application is responsible for handling navigation.\u003C/p\u003E\n\u003Cp\u003EThis can be useful when integrating UltimateAuth into an existing routing or navigation system.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022authorization-callback\u0022\u003EAuthorization Callback\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Pkce.OnAuthorized = response =\u0026gt;\n {\n // Inspect or process the authorization response.\n return Task.CompletedTask;\n };\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe callback receives:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EPkceAuthorizeResponse\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIt runs after the authorization response is issued and before the normal Hub navigation.\u003C/p\u003E\n\u003Cp\u003EUse the callback for application-specific integration, not to bypass PKCE verification.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-and-server-pkce-settings-are-different\u0022\u003EClient and Server PKCE Settings Are Different\u003C/h3\u003E\n\u003Cp\u003EClient configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AutoRedirect = true;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EServer configuration:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.Pkce.AuthorizationCodeLifetimeSeconds = 120;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe client controls how the flow is initiated and navigated.\u003C/p\u003E\n\u003Cp\u003EThe server controls the authorization code\u0027s validity and verification.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022return-url-configuration\u0022\u003E8. Return URL Configuration\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth supports several return URL configuration points.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGlobal default for interactive authentication\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin-specific default\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE-specific default\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022global-default\u0022\u003EGlobal Default\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022flow-specific-defaults\u0022\u003EFlow-Specific Defaults\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/account\u0026quot;;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFlow-specific values allow different authentication paths to use different destinations.\u003C/p\u003E\n\u003Cp\u003EAn explicitly supplied return URL for an individual operation may take precedence over these defaults.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-considerations\u0022\u003ESecurity Considerations\u003C/h3\u003E\n\u003Cp\u003EReturn URLs are navigation destinations and must be treated carefully.\u003C/p\u003E\n\u003Cp\u003EDo not redirect users to arbitrary external URLs without appropriate validation.\u003C/p\u003E\n\u003Cp\u003EOpen redirects can be abused for phishing and other attacks.\u003C/p\u003E\n\u003Cp\u003EPrefer local application routes unless cross-origin navigation is an intentional and validated part of the authentication architecture.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022automatic-refresh\u0022\u003E9. Automatic Refresh\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.AutoRefresh\u003C/code\u003E controls client-side authentication renewal.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth provides three independently configurable automatic refresh strategies.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EPurpose\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EProactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh before eligible authenticated requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERecover from supported authentication challenges\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBackground\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh independently of application requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EInterval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E5 minutes\u003C/td\u003E\n\u003Ctd\u003EInterval-based refresh eligibility\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERefreshBeforeExpiration\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E1 minute\u003C/td\u003E\n\u003Ctd\u003EJWT expiration-based refresh threshold\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.AutoRefresh.Proactive = true;\n options.AutoRefresh.Reactive = true;\n options.AutoRefresh.Background = false;\n\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n options.AutoRefresh.RefreshBeforeExpiration = TimeSpan.FromMinutes(1);\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EProactive and reactive refresh are enabled by default.\u003C/p\u003E\n\u003Cp\u003EBackground refresh is opt-in and requires an active client coordinator.\u003C/p\u003E\n\u003Cp\u003EThe client uses interval-based or JWT expiration-based scheduling according to the available managed credential.\u003C/p\u003E\n\u003Cp\u003EAll refresh strategies share coordination infrastructure within the current client scope.\u003C/p\u003E\n\u003Cp\u003EAutomatic refresh does not override server-side expiration, revocation, device binding, or rate-limiting policies.\u003C/p\u003E\n\u003Cp\u003EFor strategy selection, scheduling behavior, session policy alignment, request replay, and diagnostics, see \u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022reauthentication-options\u0022\u003E10. Reauthentication Options\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.Reauth\u003C/code\u003E controls how the Blazor session coordinator responds when refresh reports that reauthentication is required.\u003C/p\u003E\n\u003Cp\u003EThe available properties are:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EBehavior\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauthBehavior.Redirect\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERedirectPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-behaviors\u0022\u003EAvailable Behaviors\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EReauthBehavior.Redirect\nReauthBehavior.None\nReauthBehavior.RaiseEvent\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022redirect\u0022\u003ERedirect\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the coordinator receives a \u003Ccode\u003EReauthRequired\u003C/code\u003E refresh outcome, it navigates to the configured redirect path.\u003C/p\u003E\n\u003Cp\u003EIf \u003Ccode\u003ERedirectPath\u003C/code\u003E is null, the coordinator falls back to \u003Ccode\u003EEndpoints.Login\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe current Blazor coordinator uses forced navigation for this redirect.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022raise-an-event\u0022\u003ERaise an Event\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.RaiseEvent;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis allows an application to handle reauthentication through the coordinator\u0027s \u003Ccode\u003EReauthRequired\u003C/code\u003E event.\u003C/p\u003E\n\u003Cp\u003EFor example, an application may display a reauthentication dialog rather than immediately navigating.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022no-automatic-action\u0022\u003ENo Automatic Action\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Reauth.Behavior = ReauthBehavior.None;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith \u003Ccode\u003ENone\u003C/code\u003E, the coordinator does not automatically redirect or raise its reauthentication event.\u003C/p\u003E\n\u003Cp\u003EThe application must still handle unauthenticated states appropriately.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022important\u0022\u003EImportant\u003C/h3\u003E\n\u003Cp\u003EReauthentication behavior does not make an expired or revoked session valid.\u003C/p\u003E\n\u003Cp\u003EIt only controls how the client responds when authentication must be reestablished.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022multi-tenant-client-configuration\u0022\u003E11. Multi-Tenant Client Configuration\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.MultiTenant\u003C/code\u003E controls tenant propagation from the client to the authentication server.\u003C/p\u003E\n\u003Cp\u003EThe client does not independently authorize or resolve tenant ownership.\u003C/p\u003E\n\u003Cp\u003EIt carries tenant context using the configured transport.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-properties\u0022\u003EAvailable Properties\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EProperty\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEnabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EEnable tenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant identifier to propagate\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ETransport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ETenantTransport.None\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant transport mechanism\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-transports\u0022\u003EAvailable Transports\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003ETenantTransport.None\nTenantTransport.Header\nTenantTransport.Route\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022header-based-tenant-propagation\u0022\u003EHeader-Based Tenant Propagation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.Tenant = \u0026quot;tenant-a\u0026quot;;\n options.MultiTenant.Transport = TenantTransport.Header;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe server must be configured to resolve tenant information from the corresponding transport.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.EnableHeader = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022route-based-tenant-propagation\u0022\u003ERoute-Based Tenant Propagation\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.MultiTenant.Enabled = true;\n options.MultiTenant.Tenant = \u0026quot;tenant-a\u0026quot;;\n options.MultiTenant.Transport = TenantTransport.Route;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe server must expose routes compatible with tenant-based routing.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-boundary\u0022\u003ESecurity Boundary\u003C/h3\u003E\n\u003Cp\u003EA client-provided tenant identifier is not proof of tenant membership.\u003C/p\u003E\n\u003Cp\u003EThe server must validate the resolved tenant and enforce tenant isolation.\u003C/p\u003E\n\u003Cp\u003ENever rely on client-side tenant selection as an authorization boundary.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022authentication-state-events\u0022\u003E12. Authentication State Events\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003Eoptions.StateEvents\u003C/code\u003E controls how the client processes authentication-related state events.\u003C/p\u003E\n\u003Cp\u003EThe available property is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.StateEvents.HandlingMode\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EIts default is:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthStateEventHandlingMode.Patch\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022available-modes\u0022\u003EAvailable Modes\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EMode\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApply a local authentication state update\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EValidate\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevalidate authentication state after the event\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDo not update authentication state in response to the event\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022patch\u0022\u003EPatch\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EPatch\u003C/code\u003E is the default.\u003C/p\u003E\n\u003Cp\u003EIt allows the client to update local state without performing a full authentication validation for every event.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validate\u0022\u003EValidate\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Validate;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003EValidate\u003C/code\u003E causes the client to revalidate authentication state in response to events.\u003C/p\u003E\n\u003Cp\u003EThis may introduce additional requests but can be appropriate when the application prefers server-confirmed state updates.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022none\u0022\u003ENone\u003C/h3\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.None;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003E\u003Ccode\u003ENone\u003C/code\u003E disables automatic authentication state updates in response to these events.\u003C/p\u003E\n\u003Cp\u003EApplications using this mode must provide any required state synchronization through other mechanisms.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022local-events-are-not-distributed-notifications\u0022\u003ELocal Events Are Not Distributed Notifications\u003C/h3\u003E\n\u003Cp\u003EClient state events do not automatically notify every browser, device, or application instance.\u003C/p\u003E\n\u003Cp\u003EFor example, an administrator changing a user\u0027s role does not automatically push an event to that user\u0027s open browser.\u003C/p\u003E\n\u003Cp\u003EDistributed synchronization requires additional application infrastructure.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuration-from-appsettings.json\u0022\u003E13. Configuration from appsettings.json\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth Client binds the configuration section:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth:Client\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EJSON\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-json\u0022\u003E{\n \u0026quot;UltimateAuth\u0026quot;: {\n \u0026quot;Client\u0026quot;: {\n \u0026quot;AutoDetectApplicationProfile\u0026quot;: true,\n \u0026quot;DefaultReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;,\n \u0026quot;Endpoints\u0026quot;: {\n \u0026quot;BasePath\u0026quot;: \u0026quot;https://auth.example.com/auth\u0026quot;\n },\n \u0026quot;Pkce\u0026quot;: {\n \u0026quot;Enabled\u0026quot;: true,\n \u0026quot;ReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;,\n \u0026quot;AutoRedirect\u0026quot;: true\n },\n \u0026quot;AutoRefresh\u0026quot;: {\n \u0026quot;Background\u0026quot;: true,\n \u0026quot;Interval\u0026quot;: \u0026quot;00:05:00\u0026quot;\n },\n \u0026quot;Reauth\u0026quot;: {\n \u0026quot;Behavior\u0026quot;: \u0026quot;Redirect\u0026quot;,\n \u0026quot;RedirectPath\u0026quot;: \u0026quot;/login\u0026quot;\n },\n \u0026quot;StateEvents\u0026quot;: {\n \u0026quot;HandlingMode\u0026quot;: \u0026quot;Patch\u0026quot;\n }\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe example uses the standard ASP.NET Core configuration binding conventions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuration-precedence\u0022\u003EConfiguration Precedence\u003C/h3\u003E\n\u003Cp\u003EThe registration pipeline applies:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EOption type defaults.\u003C/li\u003E\n\u003Cli\u003EThe configuration delegate.\u003C/li\u003E\n\u003Cli\u003EValues from \u003Ccode\u003EUltimateAuth:Client\u003C/code\u003E.\u003C/li\u003E\n\u003Cli\u003EPost-configuration processing.\u003C/li\u003E\n\u003Cli\u003ERegistered options validation when the options are resolved.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWith:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EJSON\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-json\u0022\u003E{\n \u0026quot;UltimateAuth\u0026quot;: {\n \u0026quot;Client\u0026quot;: {\n \u0026quot;DefaultReturnUrl\u0026quot;: \u0026quot;/dashboard\u0026quot;\n }\n }\n}\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe configured return URL becomes \u003Ccode\u003E/dashboard\u003C/code\u003E.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022environment-variables\u0022\u003EEnvironment Variables\u003C/h3\u003E\n\u003Cp\u003EASP.NET Core supports double underscores for hierarchical configuration keys.\u003C/p\u003E\n\u003Cp\u003EFor example:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth__Client__Endpoints__BasePath=https://auth.example.com/auth\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis corresponds to:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUltimateAuth:Client:Endpoints:BasePath\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EUse environment-specific configuration for deployment-dependent values such as authentication server addresses and application return paths.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-validation\u0022\u003E14. Client Options Validation\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth registers validators for:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003EUAuthClientOptions\nUAuthClientEndpointOptions\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022application-profile-validation\u0022\u003EApplication Profile Validation\u003C/h3\u003E\n\u003Cp\u003EThe validator rejects a configuration where:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Eoptions.AutoDetectApplicationProfile = false;\noptions.ApplicationProfile = UAuthApplicationProfile.NotSpecified;\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAn explicit profile is required when detection is disabled.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022endpoint-validation\u0022\u003EEndpoint Validation\u003C/h3\u003E\n\u003Cp\u003EThe following endpoint properties must be present:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EEndpoints.BasePath\nEndpoints.Login\nEndpoints.Logout\nEndpoints.Refresh\nEndpoints.Validate\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EFor example, this configuration is invalid:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.Endpoints.BasePath = \u0026quot;\u0026quot;;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validation-timing\u0022\u003EValidation Timing\u003C/h3\u003E\n\u003Cp\u003EUnlike the server registration, the current client registration does not explicitly call \u003Ccode\u003EValidateOnStart()\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EValidation therefore occurs through the normal options resolution lifecycle.\u003C/p\u003E\n\u003Cp\u003EApplications that require early validation can arrange for the configured options to be resolved during startup.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022validation-scope\u0022\u003EValidation Scope\u003C/h3\u003E\n\u003Cp\u003EThe current validators check essential application profile and endpoint requirements.\u003C/p\u003E\n\u003Cp\u003EThey do not automatically validate every possible combination of client flow, server deployment, cookie behavior, and authentication mode.\u003C/p\u003E\n\u003Cp\u003EApplications should test their actual authentication flows against the deployed server configuration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-blazor-webassembly-example\u0022\u003E15. Complete Blazor WebAssembly Example\u003C/h2\u003E\n\u003Cp\u003EThe following example configures a Blazor WebAssembly client using a remote authentication server.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n // Application profile\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorWasm;\n\n // Authentication server\n options.Endpoints.BasePath = \u0026quot;https://auth.example.com/auth\u0026quot;;\n\n // Navigation\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\n // Public client security\n options.Login.AllowCredentialPost = false;\n\n // PKCE\n options.Pkce.Enabled = true;\n options.Pkce.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n options.Pkce.AutoRedirect = true;\n\n // Background refresh\n options.AutoRefresh.Background = false;\n options.AutoRefresh.Proactive = true;\n\n // Reauthentication\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n\n // State updates\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis example emphasizes PKCE-based authentication and avoids direct credential posting from a public browser client.\u003C/p\u003E\n\u003Cp\u003EThe remote server must be configured with compatible endpoints, origins, authentication modes, and credential delivery policies.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022complete-blazor-server-example\u0022\u003E16. Complete Blazor Server Example\u003C/h2\u003E\n\u003Cp\u003EThe following example configures a Blazor Server client.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003Ebuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n // Application profile\n options.AutoDetectApplicationProfile = false;\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n\n // Same-origin authentication endpoints\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n\n // Navigation\n options.DefaultReturnUrl = \u0026quot;/\u0026quot;;\n options.Login.ReturnUrl = \u0026quot;/dashboard\u0026quot;;\n\n // Background refresh\n options.AutoRefresh.Background = false;\n options.AutoRefresh.Proactive = true;\n options.AutoRefresh.Interval = TimeSpan.FromMinutes(5);\n\n // Reauthentication\n options.Reauth.Behavior = ReauthBehavior.Redirect;\n options.Reauth.RedirectPath = \u0026quot;/login\u0026quot;;\n\n // Authentication state\n options.StateEvents.HandlingMode = UAuthStateEventHandlingMode.Patch;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EBlazor Server applications can use session-oriented authentication and the corresponding server-side security policies.\u003C/p\u003E\n\u003Cp\u003EThe application must still initialize the client and session coordinator through its supported lifecycle.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022server-and-client-configuration-together\u0022\u003E17. Server and Client Configuration Together\u003C/h2\u003E\n\u003Cp\u003EAn application that hosts both UltimateAuth Server and the Blazor client adapter can configure them independently.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EC#\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-csharp\u0022\u003E// Server: authentication and security policies\nbuilder.Services.AddUltimateAuthServer(options =\u0026gt;\n{\n options.AllowedModes =\n [\n UAuthMode.PureOpaque,\n UAuthMode.Hybrid\n ];\n\n options.Session.Lifetime = TimeSpan.FromDays(7);\n options.Login.MaxFailedAttempts = 5;\n});\n\n// Client: platform integration and flow behavior\nbuilder.Services.AddUltimateAuthClientBlazor(options =\u0026gt;\n{\n options.ApplicationProfile = UAuthApplicationProfile.BlazorServer;\n options.AutoDetectApplicationProfile = false;\n options.Endpoints.BasePath = \u0026quot;/auth\u0026quot;;\n options.AutoRefresh.Proactive = true;\n});\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe two configuration objects have different responsibilities.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ERequirement\u003C/th\u003E\n\u003Cth\u003EConfigure on\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ESession lifetime\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAccess token lifetime\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ERefresh token replay policy\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ECredential recovery rules\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAllowed authentication modes\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EApplication profile\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EPKCE navigation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAutomatic proactive refresh\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EReauthentication navigation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003EAuthentication state event handling\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ETenant validation\u003C/td\u003E\n\u003Ctd\u003EServer\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003Ctd\u003EClient\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThe client cannot override server-side security decisions.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022common-configuration-mistakes\u0022\u003E18. Common Configuration Mistakes\u003C/h2\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022registering-the-core-client-and-blazor-adapter-separately\u0022\u003ERegistering the Core Client and Blazor Adapter Separately\u003C/h3\u003E\n\u003Cp\u003EUse \u003Ccode\u003EAddUltimateAuthClientBlazor()\u003C/code\u003E for Blazor applications.\u003C/p\u003E\n\u003Cp\u003EIt already registers the underlying client SDK.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022disabling-profile-detection-without-selecting-a-profile\u0022\u003EDisabling Profile Detection Without Selecting a Profile\u003C/h3\u003E\n\u003Cp\u003EWhen \u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E is false, set \u003Ccode\u003EApplicationProfile\u003C/code\u003E explicitly.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022relying-on-automatic-detection-in-an-ambiguous-hosting-environment\u0022\u003ERelying on Automatic Detection in an Ambiguous Hosting Environment\u003C/h3\u003E\n\u003Cp\u003EFor complex hosting arrangements, consider specifying the application profile explicitly.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022enabling-direct-credential-posting-in-a-public-client\u0022\u003EEnabling Direct Credential Posting in a Public Client\u003C/h3\u003E\n\u003Cp\u003EDo not enable \u003Ccode\u003EAllowCredentialPost\u003C/code\u003E for browser-hosted public clients.\u003C/p\u003E\n\u003Cp\u003EUse PKCE.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-client-auto-refresh-extends-server-lifetimes\u0022\u003EAssuming Client Auto-Refresh Extends Server Lifetimes\u003C/h3\u003E\n\u003Cp\u003EAutomatic refresh only initiates refresh operations.\u003C/p\u003E\n\u003Cp\u003EThe server controls whether refresh is permitted.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-auto-refresh-starts-automatically\u0022\u003EAssuming Auto-Refresh Starts Automatically\u003C/h3\u003E\n\u003Cp\u003EThe Blazor session coordinator must be started through the supported application lifecycle.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022configuring-only-the-client-endpoint\u0022\u003EConfiguring Only the Client Endpoint\u003C/h3\u003E\n\u003Cp\u003EThe server must expose compatible routes and allow the intended cross-origin interaction.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022treating-tenant-propagation-as-authorization\u0022\u003ETreating Tenant Propagation as Authorization\u003C/h3\u003E\n\u003Cp\u003EA tenant identifier supplied by the client does not grant access to that tenant.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022using-state-events-as-distributed-notifications\u0022\u003EUsing State Events as Distributed Notifications\u003C/h3\u003E\n\u003Cp\u003EClient events update local client state; they do not automatically synchronize all connected devices.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022assuming-every-client-setting-is-validated-at-startup\u0022\u003EAssuming Every Client Setting Is Validated at Startup\u003C/h3\u003E\n\u003Cp\u003EThe current client registration validates options when they are resolved, rather than explicitly requiring startup validation.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022client-options-quick-reference\u0022\u003E19. Client Options Quick Reference\u003C/h2\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EOption\u003C/th\u003E\n\u003Cth\u003EDefault\u003C/th\u003E\n\u003Cth\u003EDescription\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ENotSpecified\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EApplication environment\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoDetectApplicationProfile\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatic profile detection\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EDefaultReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EGlobal return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EEndpoints.BasePath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003E/auth\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication endpoint base\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ELogin return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ELogin.AllowCredentialPost\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EDirect credential posting\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.Enabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE flow support\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.ReturnUrl\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE return URL\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.AutoRedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EAutomatic PKCE navigation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EPkce.OnAuthorized\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPKCE authorization callback\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Proactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERefresh before eligible authenticated requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Reactive\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Etrue\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERecover from supported authentication challenges\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Background\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EIndependent background refresh coordination\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.Interval\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E5 minutes\u003C/td\u003E\n\u003Ctd\u003EInterval-based refresh eligibility\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EAutoRefresh.RefreshBeforeExpiration\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E1 minute\u003C/td\u003E\n\u003Ctd\u003EJWT expiration-based refresh threshold\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth.Behavior\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ERedirect\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EReauth.RedirectPath\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EReauthentication redirect\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Enabled\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Efalse\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant propagation\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Tenant\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant identifier\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EMultiTenant.Transport\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003ENone\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ETenant transport\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EStateEvents.HandlingMode\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EPatch\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EState event handling\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.BaseAddress\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003Enull\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EResource API origin; defaults to application origin\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EResource.Credentials\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003E\u003Ccode\u003EAuto\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EBrowser credential handling for resource requests\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/overview\u0022\u003EConfiguration Overview\u003C/a\u003E \u2014 Understand the configuration architecture and source precedence.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/server-options\u0022\u003EServer Options\u003C/a\u003E \u2014 Configure authentication security, sessions, tokens, and endpoints.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/configuration/advanced-configuration\u0022\u003EAdvanced Configuration\u003C/a\u003E \u2014 Explore effective options, mode resolution, and extension points.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/authentication\u0022\u003EAuthentication\u003C/a\u003E \u2014 Implement login, PKCE, refresh, and logout flows.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/automatic-refresh\u0022\u003EAutomatic Refresh\u003C/a\u003E \u2014 Configure efficient authentication renewal, automatic recovery, and refresh coordination.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/client-sdk/session-management\u0022\u003ESession Management\u003C/a\u003E \u2014 Manage authenticated sessions and revocation.\u003C/li\u003E\n\u003C/ul\u003E\n", "Headings": [ { "Id": "register-the-ultimateauth-client", @@ -168,41 +168,6 @@ "Text": "9. Automatic Refresh", "Level": 0 }, - { - "Id": "configure-automatic-refresh", - "Text": "Configure Automatic Refresh", - "Level": 1 - }, - { - "Id": "disable-automatic-refresh", - "Text": "Disable Automatic Refresh", - "Level": 1 - }, - { - "Id": "default-interval", - "Text": "Default Interval", - "Level": 1 - }, - { - "Id": "platform-behavior", - "Text": "Platform Behavior", - "Level": 1 - }, - { - "Id": "automatic-refresh-is-not-a-security-policy", - "Text": "Automatic Refresh Is Not a Security Policy", - "Level": 1 - }, - { - "Id": "automatic-refresh-does-not-guarantee-session-continuity", - "Text": "Automatic Refresh Does Not Guarantee Session Continuity", - "Level": 1 - }, - { - "Id": "coordinator-lifecycle", - "Text": "Coordinator Lifecycle", - "Level": 1 - }, { "Id": "reauthentication-options", "Text": "10. Reauthentication Options", @@ -414,6 +379,6 @@ "Level": 0 } ], - "SourceHash": "84F0639982E2B2C1F2654290837D5A975F1646905894E4EF07A5F9789520D658", + "SourceHash": "41E44B2415B87DA2D857DA48A4327DFFAF46BD79E1D3ED4FD073913572A440A8", "BuilderVersion": "1" } \ No newline at end of file diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/docs-index.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/docs-index.json index fb1a66ac..a825eb99 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/docs-index.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/docs-index.json @@ -181,45 +181,52 @@ "Group": "client", "GroupOrder": 6 }, + { + "Title": "Automatic Refresh", + "Slug": "client-sdk/automatic-refresh", + "Order": 3, + "Group": "client", + "GroupOrder": 6 + }, { "Title": "Session Management", "Slug": "client-sdk/session-management", - "Order": 3, + "Order": 4, "Group": "client", "GroupOrder": 6 }, { "Title": "User Management", "Slug": "client-sdk/user-management", - "Order": 4, + "Order": 5, "Group": "client", "GroupOrder": 6 }, { "Title": "Identifiers", "Slug": "client-sdk/identifiers", - "Order": 5, + "Order": 6, "Group": "client", "GroupOrder": 6 }, { "Title": "Credentials", "Slug": "client-sdk/credentials", - "Order": 6, + "Order": 7, "Group": "client", "GroupOrder": 6 }, { "Title": "Authorization", "Slug": "client-sdk/authorization", - "Order": 7, + "Order": 8, "Group": "client", "GroupOrder": 6 }, { "Title": "Resource API Requests", "Slug": "client-sdk/resource-api-requests", - "Order": 8, + "Order": 9, "Group": "client", "GroupOrder": 6 }, diff --git a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/sessions-devices/session-lifecycle.json b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/sessions-devices/session-lifecycle.json index 95b35aec..cd6033f2 100644 --- a/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/sessions-devices/session-lifecycle.json +++ b/docs/website/CodeBeam.UltimateAuth.Docs.Wasm/CodeBeam.UltimateAuth.Docs.Wasm.Client/wwwroot/docs/sessions-devices/session-lifecycle.json @@ -1,7 +1,7 @@ { "Slug": "sessions-devices/session-lifecycle", "Title": "Session Model \u0026 Lifecycle", - "Html": "\n\u003Cp\u003EAuthentication is more than issuing a credential and checking its expiration.\u003C/p\u003E\n\u003Cp\u003EIn stateful authentication systems, successful authentication establishes security state that must be managed throughout its lifetime. Sessions may be refreshed, extended, revoked, or invalidated in response to changes in account security.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth models this state through a structured hierarchy:\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERoot \u2192 Chain \u2192 Session\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EThis hierarchy separates account-level authentication security, device-associated session continuity, and individual authentication sessions.\u003C/p\u003E\n\u003Cp\u003EThe model provides the foundation for session management, security versioning, targeted revocation, and lifecycle enforcement.\u003C/p\u003E\n\u003Cp\u003EIts runtime behavior depends on the configured authentication mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022understanding-the-session-hierarchy\u0022\u003EUnderstanding the Session Hierarchy\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth organizes server-managed authentication state into three levels.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ELevel\u003C/th\u003E\n\u003Cth\u003ERepresents\u003C/th\u003E\n\u003Cth\u003EPrimary responsibility\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESessionRoot\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAccount-level authentication security\u003C/td\u003E\n\u003Ctd\u003EGlobal session state and security versioning\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESessionChain\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERelated session continuity\u003C/td\u003E\n\u003Ctd\u003EDevice association, activity, and chain-level control\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESession\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EIndividual authentication state\u003C/td\u003E\n\u003Ctd\u003ESession validity, expiration, and revocation\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUser Identity\n |\n \u2514\u2500\u2500 SessionRoot\n |\n \u251C\u2500\u2500 SessionChain (Desktop Browser)\n | |\n | \u251C\u2500\u2500 Session\n | \u2514\u2500\u2500 Session\n |\n \u2514\u2500\u2500 SessionChain (Mobile Application)\n |\n \u2514\u2500\u2500 Session\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is a logical representation of the hierarchy. It does not imply that every authentication mode stores the same records or maintains multiple simultaneous sessions within each chain.\u003C/p\u003E\n\u003Cp\u003EEach level addresses a different security concern.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022sessionroot-account-level-security\u0022\u003ESessionRoot: Account-Level Security\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ESessionRoot\u003C/code\u003E represents the account-level security boundary for server-managed authentication sessions.\u003C/p\u003E\n\u003Cp\u003EIt associates the authentication session hierarchy with a user identity and maintains security information relevant across that identity\u0027s sessions.\u003C/p\u003E\n\u003Cp\u003EThe root is not the user account itself.\u003C/p\u003E\n\u003Cp\u003EThe Users domain may own the user\u0027s identifiers, profile, and lifecycle. The session root belongs to authentication security management.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-responsibilities\u0022\u003ERoot Responsibilities\u003C/h3\u003E\n\u003Cp\u003EA session root provides a common boundary for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAssociating session chains with an identity.\u003C/li\u003E\n\u003Cli\u003EMaintaining account-level session security state.\u003C/li\u003E\n\u003Cli\u003ECoordinating global session invalidation.\u003C/li\u003E\n\u003Cli\u003ESupporting security version checks.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe distinction is important because changes to authentication security do not necessarily require changes to the user entity.\u003C/p\u003E\n\u003Cp\u003EFor example, invalidating existing sessions should not require recreating the user or changing the user\u0027s identifiers.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-versioning\u0022\u003ESecurity Versioning\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth\u0027s session model supports security versioning.\u003C/p\u003E\n\u003Cp\u003EA root can maintain a security version representing the current account-level authentication security state.\u003C/p\u003E\n\u003Cp\u003ESessions can retain the corresponding version from their creation.\u003C/p\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERoot.SecurityVersion = 4\nSession.SecurityVersionAtCreation = 4\n\nResult: Version matches\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAfter an account-level security invalidation:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERoot.SecurityVersion = 5\nSession.SecurityVersionAtCreation = 4\n\nResult: Version mismatch\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the applicable session validation checks detect a version mismatch, the older session is no longer valid.\u003C/p\u003E\n\u003Cp\u003EThis allows the authentication system to invalidate previously established session state through a shared security boundary.\u003C/p\u003E\n\u003Cp\u003EThe effect on already-issued JWT access tokens still depends on whether protected requests consult current server-side security state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022sessionchain-session-continuity\u0022\u003ESessionChain: Session Continuity\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ESessionChain\u003C/code\u003E represents a logical grouping of related authentication sessions.\u003C/p\u003E\n\u003Cp\u003EA chain can be associated with a particular device or client environment, allowing session activity to be managed within a recognizable continuity boundary.\u003C/p\u003E\n\u003Cp\u003EFor example, a user may have separate chains for a desktop browser and a mobile application.\u003C/p\u003E\n\u003Cp\u003EHowever, a chain is not a physical device identity or a guarantee that the device has been cryptographically verified.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-responsibilities\u0022\u003EChain Responsibilities\u003C/h3\u003E\n\u003Cp\u003EA session chain can provide a boundary for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAssociating related sessions.\u003C/li\u003E\n\u003Cli\u003EMaintaining device or client context.\u003C/li\u003E\n\u003Cli\u003ERecording relevant activity.\u003C/li\u003E\n\u003Cli\u003ETracking session rotation.\u003C/li\u003E\n\u003Cli\u003EApplying chain-level security operations.\u003C/li\u003E\n\u003Cli\u003ERevoking related sessions together.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis allows UltimateAuth to distinguish between the lifecycle of an individual session and the continuity of the environment associated with it.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022device-association\u0022\u003EDevice Association\u003C/h3\u003E\n\u003Cp\u003EA chain may include device-related information such as a device identifier, platform, operating system, or browser.\u003C/p\u003E\n\u003Cp\u003EThese attributes help describe the client environment.\u003C/p\u003E\n\u003Cp\u003EThey must not be treated as independent proof of device ownership.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E for the device association model and its security boundaries.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-individual-authentication-state\u0022\u003ESession: Individual Authentication State\u003C/h2\u003E\n\u003Cp\u003EA \u003Ccode\u003ESession\u003C/code\u003E represents an individual unit of server-managed authentication state.\u003C/p\u003E\n\u003Cp\u003EIt is associated with a chain and participates in the validity rules established by the authentication mode and session configuration.\u003C/p\u003E\n\u003Cp\u003EA session may contain information relevant to:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EIts associated identity and chain.\u003C/li\u003E\n\u003Cli\u003ECreation and expiration.\u003C/li\u003E\n\u003Cli\u003ERevocation status.\u003C/li\u003E\n\u003Cli\u003ESecurity version at creation.\u003C/li\u003E\n\u003Cli\u003EAuthentication lifecycle and validity.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA session is not necessarily equivalent to an access token.\u003C/p\u003E\n\u003Cp\u003EIn opaque authentication modes, a client credential may reference server-managed session state.\u003C/p\u003E\n\u003Cp\u003EIn JWT-based modes, an issued access token may be validated locally without consulting the session hierarchy on every protected request.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThe token is authentication material. The session is a security-state concept.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EKeeping these concepts separate is essential for understanding UltimateAuth\u0027s authentication modes.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-creation\u0022\u003ESession Creation\u003C/h2\u003E\n\u003Cp\u003EA session lifecycle begins when an authentication flow successfully establishes the required authentication state.\u003C/p\u003E\n\u003Cp\u003EFor modes using the server-managed session hierarchy, the process conceptually involves:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EResolving the authenticated user identity.\u003C/li\u003E\n\u003Cli\u003EResolving or establishing the corresponding session root.\u003C/li\u003E\n\u003Cli\u003EDetermining the appropriate session chain.\u003C/li\u003E\n\u003Cli\u003ECreating or updating the required session state.\u003C/li\u003E\n\u003Cli\u003EIssuing the authentication material required by the selected mode.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe authentication flow must satisfy its verification and security requirements before establishing a valid authenticated session.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-resolution\u0022\u003ERoot Resolution\u003C/h3\u003E\n\u003Cp\u003EAn existing account-level session root can be reused when appropriate.\u003C/p\u003E\n\u003Cp\u003EIf the required root does not exist, the session infrastructure can establish it as part of session creation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-resolution\u0022\u003EChain Resolution\u003C/h3\u003E\n\u003Cp\u003EThe session infrastructure determines whether authentication should be associated with an existing chain or a new chain.\u003C/p\u003E\n\u003Cp\u003EA previously observed device identifier does not automatically establish that an existing chain is valid or eligible for reuse.\u003C/p\u003E\n\u003Cp\u003EThe decision must respect the applicable chain lifecycle and security conditions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-establishment\u0022\u003ESession Establishment\u003C/h3\u003E\n\u003Cp\u003EOnce the appropriate security context has been established, the authentication system creates or updates the session state required by the authentication mode.\u003C/p\u003E\n\u003Cp\u003EThe resulting client credential is then issued according to that mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022active-session-usage\u0022\u003EActive Session Usage\u003C/h2\u003E\n\u003Cp\u003EAfter authentication, the client presents the appropriate authentication material when accessing protected resources.\u003C/p\u003E\n\u003Cp\u003EWhat happens next depends on the configured mode.\u003C/p\u003E\n\u003Cp\u003EIn session-authoritative modes, protected requests can be evaluated against current server-managed session state.\u003C/p\u003E\n\u003Cp\u003EIn locally validated JWT modes, protected requests may be authenticated using the token\u0027s cryptographic validity and claims without loading the current session record.\u003C/p\u003E\n\u003Cp\u003EThis distinction affects session activity tracking, expiration enforcement, and revocation behavior.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022touch-operations\u0022\u003ETouch Operations\u003C/h3\u003E\n\u003Cp\u003EA touch operation records qualifying session activity.\u003C/p\u003E\n\u003Cp\u003EDepending on the session strategy, it may update information such as:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ELastSeenAt\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003ERelevant session activity or expiration state\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ETouch behavior is not necessarily performed for every HTTP request.\u003C/p\u003E\n\u003Cp\u003EApplications should not assume that an authenticated request always results in a persistent session update.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022sliding-expiration\u0022\u003ESliding Expiration\u003C/h3\u003E\n\u003Cp\u003ESliding expiration allows eligible authentication state to remain valid as qualifying activity occurs.\u003C/p\u003E\n\u003Cp\u003EUnlike a fixed expiration, sliding expiration can extend a session\u0027s usable lifetime according to configured rules.\u003C/p\u003E\n\u003Cp\u003EHowever, sliding expiration does not necessarily remove absolute lifetime restrictions.\u003C/p\u003E\n\u003Cp\u003EA session may still become invalid when a maximum permitted lifetime is reached.\u003C/p\u003E\n\u003Cp\u003EThe exact behavior depends on the selected authentication mode and its session configuration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-and-rotation\u0022\u003ERefresh and Rotation\u003C/h2\u003E\n\u003Cp\u003ERefresh and rotation are related to session lifecycle but are not identical operations.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERefresh\u003C/strong\u003E is an authentication operation used to continue or renew authentication state.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERotation\u003C/strong\u003E replaces authentication material or session-related credentials according to the configured security strategy.\u003C/p\u003E\n\u003Cp\u003EThe relationship between these operations varies by authentication mode.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022pureopaque\u0022\u003EPureOpaque\u003C/h3\u003E\n\u003Cp\u003EPureOpaque uses server-authoritative opaque session authentication.\u003C/p\u003E\n\u003Cp\u003EIt does not require a separate access-token and refresh-token pair.\u003C/p\u003E\n\u003Cp\u003ESession continuity and activity management are handled through the applicable opaque session lifecycle.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022hybrid\u0022\u003EHybrid\u003C/h3\u003E\n\u003Cp\u003EHybrid uses distinct opaque access and refresh credentials backed by server-authoritative session state.\u003C/p\u003E\n\u003Cp\u003ERefresh operations can renew authentication material while preserving the appropriate session or chain relationship.\u003C/p\u003E\n\u003Cp\u003EThe exact rotation behavior follows the configured refresh strategy.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022semihybrid\u0022\u003ESemiHybrid\u003C/h3\u003E\n\u003Cp\u003ESemiHybrid uses JWT access tokens while maintaining server-side session state for lifecycle operations such as refresh and logout.\u003C/p\u003E\n\u003Cp\u003ERefresh may issue new JWT access material and update the relevant server-managed state.\u003C/p\u003E\n\u003Cp\u003EAlready-issued access tokens may remain valid until expiration because protected requests do not necessarily consult that state.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt\u0022\u003EPureJwt\u003C/h3\u003E\n\u003Cp\u003EPureJwt primarily relies on stateless JWT validation for protected requests.\u003C/p\u003E\n\u003Cp\u003EA refresh mechanism may use an independent refresh store, but the server-managed Root \u2192 Chain \u2192 Session hierarchy must not be assumed to govern every protected request.\u003C/p\u003E\n\u003Cp\u003EThis is an important distinction between the framework\u0027s common authentication concepts and the persistence requirements of individual modes.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-expiration\u0022\u003ESession Expiration\u003C/h2\u003E\n\u003Cp\u003ESession expiration defines when authentication state is no longer eligible for continued use.\u003C/p\u003E\n\u003Cp\u003EDepending on the authentication mode and configuration, expiration may involve:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EExpiration mechanism\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EFixed lifetime\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state expires after a defined duration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EIdle timeout\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state expires after insufficient qualifying activity\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESliding expiration\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EEligible activity extends the usable lifetime\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAbsolute expiration\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state cannot extend beyond a maximum lifetime\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese mechanisms are not necessarily all enabled or applicable in every authentication mode.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022expired-versus-revoked\u0022\u003EExpired Versus Revoked\u003C/h3\u003E\n\u003Cp\u003EExpiration and revocation represent different reasons for invalidation.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EExpiration\u003C/strong\u003E occurs because a configured time-based condition has been reached.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERevocation\u003C/strong\u003E occurs because authentication state has been explicitly invalidated through a security operation.\u003C/p\u003E\n\u003Cp\u003EBoth can make a session unusable, but they represent different lifecycle events and may be recorded or enforced differently.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-revocation\u0022\u003ESession Revocation\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth\u0027s hierarchical session model supports security operations at different levels.\u003C/p\u003E\n\u003Cp\u003EThe scope of revocation determines how broadly authentication state is affected.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-level-revocation\u0022\u003ESession-Level Revocation\u003C/h3\u003E\n\u003Cp\u003ESession-level revocation targets an individual session.\u003C/p\u003E\n\u003Cp\u003EIt is appropriate when a specific authentication instance must be invalidated without necessarily affecting other sessions associated with the same user.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-level-revocation\u0022\u003EChain-Level Revocation\u003C/h3\u003E\n\u003Cp\u003EChain-level revocation targets the session continuity represented by a chain.\u003C/p\u003E\n\u003Cp\u003EIt allows related sessions to be invalidated together.\u003C/p\u003E\n\u003Cp\u003EThis can be useful when a particular client environment is suspected of compromise or when a user wants to terminate sessions associated with one device context.\u003C/p\u003E\n\u003Cp\u003ERevoking a chain does not mean that the corresponding physical device is permanently blocked from authenticating again.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-level-revocation\u0022\u003ERoot-Level Revocation\u003C/h3\u003E\n\u003Cp\u003ERoot-level revocation affects the account-level authentication security boundary.\u003C/p\u003E\n\u003Cp\u003EIt provides a mechanism for invalidating authentication state associated with the user\u0027s session hierarchy.\u003C/p\u003E\n\u003Cp\u003ESecurity version changes can support this operation by making previously created sessions fail subsequent version validation.\u003C/p\u003E\n\u003Cp\u003EThis is useful for broad security responses, including operations that require invalidating all applicable existing sessions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022revocation-scope\u0022\u003ERevocation Scope\u003C/h3\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ESession revocation\n \u2514\u2500\u2500 One session\n\nChain revocation\n \u2514\u2500\u2500 Related sessions in one chain\n\nRoot revocation\n \u2514\u2500\u2500 Account-level session hierarchy\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe effective invalidation of protected requests depends on the authentication mode.\u003C/p\u003E\n\u003Cp\u003EIn particular, server-side revocation does not automatically invalidate a previously issued JWT that is still cryptographically valid and is not checked against current revocation state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-security-and-credential-changes\u0022\u003ESession Security and Credential Changes\u003C/h2\u003E\n\u003Cp\u003ESession lifecycle is closely related to credential security.\u003C/p\u003E\n\u003Cp\u003EA password change or recovery operation may require existing authentication sessions to be preserved or revoked.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth supports session handling policies for credential changes and resets, including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EPolicy\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EKeepAll\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPreserve applicable existing sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EKeepCurrent\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPreserve the current session while revoking other applicable sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERevokeAll\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke all applicable sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese policies allow applications to choose the security response appropriate to the operation.\u003C/p\u003E\n\u003Cp\u003EFor example, an authenticated password change and an anonymous password recovery operation may require different session handling.\u003C/p\u003E\n\u003Cp\u003EThe Credentials domain initiates the relevant security behavior, while the session infrastructure applies the corresponding lifecycle operations.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/plugin-domains/credentials\u0022\u003ECredentials\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-configuration\u0022\u003ESession Configuration\u003C/h2\u003E\n\u003Cp\u003ESession behavior is configured through UltimateAuth\u0027s session options, including \u003Ccode\u003EUAuthSessionOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe configuration model governs supported aspects of session lifecycle such as:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ESession lifetimes.\u003C/li\u003E\n\u003Cli\u003EActivity and expiration behavior.\u003C/li\u003E\n\u003Cli\u003ERefresh and rotation strategies.\u003C/li\u003E\n\u003Cli\u003ESession and chain limits.\u003C/li\u003E\n\u003Cli\u003EDevice-related session constraints.\u003C/li\u003E\n\u003Cli\u003ERevocation and lifecycle enforcement.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ENot every option applies to every authentication mode.\u003C/p\u003E\n\u003Cp\u003EFor example, a configuration setting that controls server-side session activity may not affect the validation of a stateless JWT access token.\u003C/p\u003E\n\u003Cp\u003EApplications should configure session behavior with the selected authentication mode and its enforcement boundaries in mind.\u003C/p\u003E\n\u003Cp\u003EDetailed configuration examples belong in the configuration reference and How-to Guides.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022architectural-perspective\u0022\u003EArchitectural Perspective\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth separates authentication identity, session continuity, and individual authentication state.\u003C/p\u003E\n\u003Cp\u003EThe Root \u2192 Chain \u2192 Session hierarchy expresses those responsibilities at different security levels:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ERoot\u003C/strong\u003E provides account-level authentication security.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EChain\u003C/strong\u003E organizes related session continuity.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession\u003C/strong\u003E represents individual server-managed authentication state.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis structure supports targeted session management without requiring all security operations to act on every session belonging to a user.\u003C/p\u003E\n\u003Cp\u003EAt the same time, UltimateAuth does not assume that every authentication mode requires identical server-side state.\u003C/p\u003E\n\u003Cp\u003EThe hierarchy is most directly relevant to session-managed authentication, while JWT-based modes preserve their own validation and lifecycle characteristics.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EAuthentication establishes trust. Session management determines how that trust is maintained, renewed, and invalidated over time.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E \u2014 Device context, chain association, and device-aware session management.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/session-security\u0022\u003ESession Security\u003C/a\u003E \u2014 Session expiration, rotation, revocation, and security controls.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E \u2014 Understand how session behavior differs between modes.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/request-lifecycle\u0022\u003ERequest Lifecycle\u003C/a\u003E \u2014 Learn how protected requests validate authentication state.\u003C/li\u003E\n\u003C/ul\u003E\n", + "Html": "\n\u003Cp\u003EAuthentication is more than issuing a credential and checking its expiration.\u003C/p\u003E\n\u003Cp\u003EIn stateful authentication systems, successful authentication establishes security state that must be managed throughout its lifetime. Sessions may be refreshed, extended, revoked, or invalidated in response to changes in account security.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth models this state through a structured hierarchy:\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERoot \u2192 Chain \u2192 Session\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EThis hierarchy separates account-level authentication security, device-associated session continuity, and individual authentication sessions.\u003C/p\u003E\n\u003Cp\u003EThe model provides the foundation for session management, security versioning, targeted revocation, and lifecycle enforcement.\u003C/p\u003E\n\u003Cp\u003EIts runtime behavior depends on the configured authentication mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022understanding-the-session-hierarchy\u0022\u003EUnderstanding the Session Hierarchy\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth organizes server-managed authentication state into three levels.\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003ELevel\u003C/th\u003E\n\u003Cth\u003ERepresents\u003C/th\u003E\n\u003Cth\u003EPrimary responsibility\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESessionRoot\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAccount-level authentication security\u003C/td\u003E\n\u003Ctd\u003EGlobal session state and security versioning\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESessionChain\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003ERelated session continuity\u003C/td\u003E\n\u003Ctd\u003EDevice association, activity, and chain-level control\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESession\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EIndividual authentication state\u003C/td\u003E\n\u003Ctd\u003ESession validity, expiration, and revocation\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003EUser Identity\n |\n \u2514\u2500\u2500 SessionRoot\n |\n \u251C\u2500\u2500 SessionChain (Desktop Browser)\n | |\n | \u251C\u2500\u2500 Session\n | \u2514\u2500\u2500 Session\n |\n \u2514\u2500\u2500 SessionChain (Mobile Application)\n |\n \u2514\u2500\u2500 Session\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThis is a logical representation of the hierarchy. It does not imply that every authentication mode stores the same records or maintains multiple simultaneous sessions within each chain.\u003C/p\u003E\n\u003Cp\u003EEach level addresses a different security concern.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022sessionroot-account-level-security\u0022\u003ESessionRoot: Account-Level Security\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ESessionRoot\u003C/code\u003E represents the account-level security boundary for server-managed authentication sessions.\u003C/p\u003E\n\u003Cp\u003EIt associates the authentication session hierarchy with a user identity and maintains security information relevant across that identity\u0027s sessions.\u003C/p\u003E\n\u003Cp\u003EThe root is not the user account itself.\u003C/p\u003E\n\u003Cp\u003EThe Users domain may own the user\u0027s identifiers, profile, and lifecycle. The session root belongs to authentication security management.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-responsibilities\u0022\u003ERoot Responsibilities\u003C/h3\u003E\n\u003Cp\u003EA session root provides a common boundary for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAssociating session chains with an identity.\u003C/li\u003E\n\u003Cli\u003EMaintaining account-level session security state.\u003C/li\u003E\n\u003Cli\u003ECoordinating global session invalidation.\u003C/li\u003E\n\u003Cli\u003ESupporting security version checks.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThe distinction is important because changes to authentication security do not necessarily require changes to the user entity.\u003C/p\u003E\n\u003Cp\u003EFor example, invalidating existing sessions should not require recreating the user or changing the user\u0027s identifiers.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022security-versioning\u0022\u003ESecurity Versioning\u003C/h3\u003E\n\u003Cp\u003EUltimateAuth\u0027s session model supports security versioning.\u003C/p\u003E\n\u003Cp\u003EA root can maintain a security version representing the current account-level authentication security state.\u003C/p\u003E\n\u003Cp\u003ESessions can retain the corresponding version from their creation.\u003C/p\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERoot.SecurityVersion = 4\nSession.SecurityVersionAtCreation = 4\n\nResult: Version matches\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EAfter an account-level security invalidation:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ERoot.SecurityVersion = 5\nSession.SecurityVersionAtCreation = 4\n\nResult: Version mismatch\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EWhen the applicable session validation checks detect a version mismatch, the older session is no longer valid.\u003C/p\u003E\n\u003Cp\u003EThis allows the authentication system to invalidate previously established session state through a shared security boundary.\u003C/p\u003E\n\u003Cp\u003EThe effect on already-issued JWT access tokens still depends on whether protected requests consult current server-side security state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022sessionchain-session-continuity\u0022\u003ESessionChain: Session Continuity\u003C/h2\u003E\n\u003Cp\u003E\u003Ccode\u003ESessionChain\u003C/code\u003E represents a logical grouping of related authentication sessions.\u003C/p\u003E\n\u003Cp\u003EA chain can be associated with a particular device or client environment, allowing session activity to be managed within a recognizable continuity boundary.\u003C/p\u003E\n\u003Cp\u003EFor example, a user may have separate chains for a desktop browser and a mobile application.\u003C/p\u003E\n\u003Cp\u003EHowever, a chain is not a physical device identity or a guarantee that the device has been cryptographically verified.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-responsibilities\u0022\u003EChain Responsibilities\u003C/h3\u003E\n\u003Cp\u003EA session chain can provide a boundary for:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EAssociating related sessions.\u003C/li\u003E\n\u003Cli\u003EMaintaining device or client context.\u003C/li\u003E\n\u003Cli\u003ERecording relevant activity.\u003C/li\u003E\n\u003Cli\u003ETracking session rotation.\u003C/li\u003E\n\u003Cli\u003EApplying chain-level security operations.\u003C/li\u003E\n\u003Cli\u003ERevoking related sessions together.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis allows UltimateAuth to distinguish between the lifecycle of an individual session and the continuity of the environment associated with it.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022device-association\u0022\u003EDevice Association\u003C/h3\u003E\n\u003Cp\u003EA chain may include device-related information such as a device identifier, platform, operating system, or browser.\u003C/p\u003E\n\u003Cp\u003EThese attributes help describe the client environment.\u003C/p\u003E\n\u003Cp\u003EThey must not be treated as independent proof of device ownership.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E for the device association model and its security boundaries.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-individual-authentication-state\u0022\u003ESession: Individual Authentication State\u003C/h2\u003E\n\u003Cp\u003EA \u003Ccode\u003ESession\u003C/code\u003E represents an individual unit of server-managed authentication state.\u003C/p\u003E\n\u003Cp\u003EIt is associated with a chain and participates in the validity rules established by the authentication mode and session configuration.\u003C/p\u003E\n\u003Cp\u003EA session may contain information relevant to:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003EIts associated identity and chain.\u003C/li\u003E\n\u003Cli\u003ECreation and expiration.\u003C/li\u003E\n\u003Cli\u003ERevocation status.\u003C/li\u003E\n\u003Cli\u003ESecurity version at creation.\u003C/li\u003E\n\u003Cli\u003EAuthentication lifecycle and validity.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EA session is not necessarily equivalent to an access token.\u003C/p\u003E\n\u003Cp\u003EIn opaque authentication modes, a client credential may reference server-managed session state.\u003C/p\u003E\n\u003Cp\u003EIn JWT-based modes, an issued access token may be validated locally without consulting the session hierarchy on every protected request.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EThe token is authentication material. The session is a security-state concept.\u003C/strong\u003E\u003C/p\u003E\n\u003Cp\u003EKeeping these concepts separate is essential for understanding UltimateAuth\u0027s authentication modes.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-creation\u0022\u003ESession Creation\u003C/h2\u003E\n\u003Cp\u003EA session lifecycle begins when an authentication flow successfully establishes the required authentication state.\u003C/p\u003E\n\u003Cp\u003EFor modes using the server-managed session hierarchy, the process conceptually involves:\u003C/p\u003E\n\u003Col\u003E\n\u003Cli\u003EResolving the authenticated user identity.\u003C/li\u003E\n\u003Cli\u003EResolving or establishing the corresponding session root.\u003C/li\u003E\n\u003Cli\u003EDetermining the appropriate session chain.\u003C/li\u003E\n\u003Cli\u003ECreating or updating the required session state.\u003C/li\u003E\n\u003Cli\u003EIssuing the authentication material required by the selected mode.\u003C/li\u003E\n\u003C/ol\u003E\n\u003Cp\u003EThe authentication flow must satisfy its verification and security requirements before establishing a valid authenticated session.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-resolution\u0022\u003ERoot Resolution\u003C/h3\u003E\n\u003Cp\u003EAn existing account-level session root can be reused when appropriate.\u003C/p\u003E\n\u003Cp\u003EIf the required root does not exist, the session infrastructure can establish it as part of session creation.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-resolution\u0022\u003EChain Resolution\u003C/h3\u003E\n\u003Cp\u003EThe session infrastructure determines whether authentication should be associated with an existing chain or a new chain.\u003C/p\u003E\n\u003Cp\u003EA previously observed device identifier does not automatically establish that an existing chain is valid or eligible for reuse.\u003C/p\u003E\n\u003Cp\u003EThe decision must respect the applicable chain lifecycle and security conditions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-establishment\u0022\u003ESession Establishment\u003C/h3\u003E\n\u003Cp\u003EOnce the appropriate security context has been established, the authentication system creates or updates the session state required by the authentication mode.\u003C/p\u003E\n\u003Cp\u003EThe resulting client credential is then issued according to that mode.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022active-session-usage\u0022\u003EActive Session Usage\u003C/h2\u003E\n\u003Cp\u003EAfter authentication, the client presents the appropriate authentication material when accessing protected resources.\u003C/p\u003E\n\u003Cp\u003EWhat happens next depends on the configured mode.\u003C/p\u003E\n\u003Cp\u003EIn session-authoritative modes, protected requests can be evaluated against current server-managed session state.\u003C/p\u003E\n\u003Cp\u003EIn locally validated JWT modes, protected requests may be authenticated using the token\u0027s cryptographic validity and claims without loading the current session record.\u003C/p\u003E\n\u003Cp\u003EThis distinction affects session activity tracking, expiration enforcement, and revocation behavior.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022touch-operations\u0022\u003ETouch Operations\u003C/h3\u003E\n\u003Cp\u003EA touch operation records qualifying session activity.\u003C/p\u003E\n\u003Cp\u003EDepending on the session strategy, it may update information such as:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ccode\u003ELastSeenAt\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003E\u003Ccode\u003ETouchCount\u003C/code\u003E\u003C/li\u003E\n\u003Cli\u003ERelevant session activity or expiration state\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ETouch behavior is not necessarily performed for every HTTP request.\u003C/p\u003E\n\u003Cp\u003EApplications should not assume that an authenticated request always results in a persistent session update.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022sliding-expiration\u0022\u003ESliding Expiration\u003C/h3\u003E\n\u003Cp\u003ESliding expiration allows eligible authentication state to remain valid as qualifying activity occurs.\u003C/p\u003E\n\u003Cp\u003EUnlike a fixed expiration, sliding expiration can extend a session\u0027s usable lifetime according to configured rules.\u003C/p\u003E\n\u003Cp\u003EHowever, sliding expiration does not necessarily remove absolute lifetime restrictions.\u003C/p\u003E\n\u003Cp\u003EA session may still become invalid when a maximum permitted lifetime is reached.\u003C/p\u003E\n\u003Cp\u003EThe exact behavior depends on the selected authentication mode and its session configuration.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022refresh-and-rotation\u0022\u003ERefresh and Rotation\u003C/h2\u003E\n\u003Cp\u003ERefresh and rotation are related to session lifecycle but are not identical operations.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERefresh\u003C/strong\u003E is an authentication operation used to continue or renew authentication state.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERotation\u003C/strong\u003E replaces authentication material or session-related credentials according to the configured security strategy.\u003C/p\u003E\n\u003Cp\u003EThe relationship between these operations varies by authentication mode.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022pureopaque\u0022\u003EPureOpaque\u003C/h3\u003E\n\u003Cp\u003EPureOpaque uses server-authoritative opaque session authentication.\u003C/p\u003E\n\u003Cp\u003EIt does not require a separate access-token and refresh-token pair.\u003C/p\u003E\n\u003Cp\u003ESession continuity and activity management are handled through the applicable opaque session lifecycle.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022hybrid\u0022\u003EHybrid\u003C/h3\u003E\n\u003Cp\u003EHybrid combines server-authoritative session state with additional access-token and refresh-token lifecycles.\u003C/p\u003E\n\u003Cp\u003ERefresh operations can renew authentication material while preserving the appropriate session or chain relationship.\u003C/p\u003E\n\u003Cp\u003EThe exact rotation behavior follows the configured refresh strategy.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022semihybrid\u0022\u003ESemiHybrid\u003C/h3\u003E\n\u003Cp\u003ESemiHybrid uses JWT access tokens while maintaining server-side session state for lifecycle operations such as refresh and logout.\u003C/p\u003E\n\u003Cp\u003ERefresh may issue new JWT access material and update the relevant server-managed state.\u003C/p\u003E\n\u003Cp\u003EAlready-issued access tokens may remain valid until expiration because protected requests do not necessarily consult that state.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022purejwt\u0022\u003EPureJwt\u003C/h3\u003E\n\u003Cp\u003EPureJwt primarily relies on stateless JWT validation for protected requests.\u003C/p\u003E\n\u003Cp\u003EA refresh mechanism may use an independent refresh store, but the server-managed Root \u2192 Chain \u2192 Session hierarchy must not be assumed to govern every protected request.\u003C/p\u003E\n\u003Cp\u003EThis is an important distinction between the framework\u0027s common authentication concepts and the persistence requirements of individual modes.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-expiration\u0022\u003ESession Expiration\u003C/h2\u003E\n\u003Cp\u003ESession expiration defines when authentication state is no longer eligible for continued use.\u003C/p\u003E\n\u003Cp\u003EDepending on the authentication mode and configuration, expiration may involve:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EExpiration mechanism\u003C/th\u003E\n\u003Cth\u003EMeaning\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EFixed lifetime\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state expires after a defined duration\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EIdle timeout\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state expires after insufficient qualifying activity\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003ESliding expiration\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EEligible activity extends the usable lifetime\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Cstrong\u003EAbsolute expiration\u003C/strong\u003E\u003C/td\u003E\n\u003Ctd\u003EAuthentication state cannot extend beyond a maximum lifetime\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese mechanisms are not necessarily all enabled or applicable in every authentication mode.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022expired-versus-revoked\u0022\u003EExpired Versus Revoked\u003C/h3\u003E\n\u003Cp\u003EExpiration and revocation represent different reasons for invalidation.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EExpiration\u003C/strong\u003E occurs because a configured time-based condition has been reached.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003ERevocation\u003C/strong\u003E occurs because authentication state has been explicitly invalidated through a security operation.\u003C/p\u003E\n\u003Cp\u003EBoth can make a session unusable, but they represent different lifecycle events and may be recorded or enforced differently.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-revocation\u0022\u003ESession Revocation\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth\u0027s hierarchical session model supports security operations at different levels.\u003C/p\u003E\n\u003Cp\u003EThe scope of revocation determines how broadly authentication state is affected.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-level-revocation\u0022\u003ESession-Level Revocation\u003C/h3\u003E\n\u003Cp\u003ESession-level revocation targets an individual session.\u003C/p\u003E\n\u003Cp\u003EIt is appropriate when a specific authentication instance must be invalidated without necessarily affecting other sessions associated with the same user.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022chain-level-revocation\u0022\u003EChain-Level Revocation\u003C/h3\u003E\n\u003Cp\u003EChain-level revocation targets the session continuity represented by a chain.\u003C/p\u003E\n\u003Cp\u003EIt allows related sessions to be invalidated together.\u003C/p\u003E\n\u003Cp\u003EThis can be useful when a particular client environment is suspected of compromise or when a user wants to terminate sessions associated with one device context.\u003C/p\u003E\n\u003Cp\u003ERevoking a chain does not mean that the corresponding physical device is permanently blocked from authenticating again.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022root-level-revocation\u0022\u003ERoot-Level Revocation\u003C/h3\u003E\n\u003Cp\u003ERoot-level revocation affects the account-level authentication security boundary.\u003C/p\u003E\n\u003Cp\u003EIt provides a mechanism for invalidating authentication state associated with the user\u0027s session hierarchy.\u003C/p\u003E\n\u003Cp\u003ESecurity version changes can support this operation by making previously created sessions fail subsequent version validation.\u003C/p\u003E\n\u003Cp\u003EThis is useful for broad security responses, including operations that require invalidating all applicable existing sessions.\u003C/p\u003E\n\u003Ch3 class=\u0022mud-scrollspy-section\u0022 id=\u0022revocation-scope\u0022\u003ERevocation Scope\u003C/h3\u003E\n\u003Cp\u003EConceptually:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-code-wrapper\u0022\u003E\u003Cdiv class=\u0022docs-code-header\u0022\u003E\u003Cspan class=\u0022docs-code-language\u0022\u003EText\u003C/span\u003E\u003Cbutton type=\u0022button\u0022 class=\u0022docs-code-copy\u0022 aria-label=\u0022Copy code\u0022\u003ECopy\u003C/button\u003E\u003C/div\u003E\u003Cpre\u003E\u003Ccode class=\u0022language-text\u0022\u003ESession revocation\n \u2514\u2500\u2500 One session\n\nChain revocation\n \u2514\u2500\u2500 Related sessions in one chain\n\nRoot revocation\n \u2514\u2500\u2500 Account-level session hierarchy\n\u003C/code\u003E\u003C/pre\u003E\u003C/div\u003E\n\u003Cp\u003EThe effective invalidation of protected requests depends on the authentication mode.\u003C/p\u003E\n\u003Cp\u003EIn particular, server-side revocation does not automatically invalidate a previously issued JWT that is still cryptographically valid and is not checked against current revocation state.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-security-and-credential-changes\u0022\u003ESession Security and Credential Changes\u003C/h2\u003E\n\u003Cp\u003ESession lifecycle is closely related to credential security.\u003C/p\u003E\n\u003Cp\u003EA password change or recovery operation may require existing authentication sessions to be preserved or revoked.\u003C/p\u003E\n\u003Cp\u003EUltimateAuth supports session handling policies for credential changes and resets, including:\u003C/p\u003E\n\u003Cdiv class=\u0022docs-table-wrapper\u0022\u003E\u003Ctable\u003E\n\u003Cthead\u003E\n\u003Ctr\u003E\n\u003Cth\u003EPolicy\u003C/th\u003E\n\u003Cth\u003EBehavior\u003C/th\u003E\n\u003C/tr\u003E\n\u003C/thead\u003E\n\u003Ctbody\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EKeepAll\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPreserve applicable existing sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003EKeepCurrent\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003EPreserve the current session while revoking other applicable sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003Ctr\u003E\n\u003Ctd\u003E\u003Ccode\u003ERevokeAll\u003C/code\u003E\u003C/td\u003E\n\u003Ctd\u003ERevoke all applicable sessions\u003C/td\u003E\n\u003C/tr\u003E\n\u003C/tbody\u003E\n\u003C/table\u003E\u003C/div\u003E\n\u003Cp\u003EThese policies allow applications to choose the security response appropriate to the operation.\u003C/p\u003E\n\u003Cp\u003EFor example, an authenticated password change and an anonymous password recovery operation may require different session handling.\u003C/p\u003E\n\u003Cp\u003EThe Credentials domain initiates the relevant security behavior, while the session infrastructure applies the corresponding lifecycle operations.\u003C/p\u003E\n\u003Cp\u003ESee \u003Ca href=\u0022/docs/plugin-domains/credentials\u0022\u003ECredentials\u003C/a\u003E.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022session-configuration\u0022\u003ESession Configuration\u003C/h2\u003E\n\u003Cp\u003ESession behavior is configured through UltimateAuth\u0027s session options, including \u003Ccode\u003EUAuthSessionOptions\u003C/code\u003E.\u003C/p\u003E\n\u003Cp\u003EThe configuration model governs supported aspects of session lifecycle such as:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003ESession lifetimes.\u003C/li\u003E\n\u003Cli\u003EActivity and expiration behavior.\u003C/li\u003E\n\u003Cli\u003ERefresh and rotation strategies.\u003C/li\u003E\n\u003Cli\u003ESession and chain limits.\u003C/li\u003E\n\u003Cli\u003EDevice-related session constraints.\u003C/li\u003E\n\u003Cli\u003ERevocation and lifecycle enforcement.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003ENot every option applies to every authentication mode.\u003C/p\u003E\n\u003Cp\u003EFor example, a configuration setting that controls server-side session activity may not affect the validation of a stateless JWT access token.\u003C/p\u003E\n\u003Cp\u003EApplications should configure session behavior with the selected authentication mode and its enforcement boundaries in mind.\u003C/p\u003E\n\u003Cp\u003EDetailed configuration examples belong in the configuration reference and How-to Guides.\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022architectural-perspective\u0022\u003EArchitectural Perspective\u003C/h2\u003E\n\u003Cp\u003EUltimateAuth separates authentication identity, session continuity, and individual authentication state.\u003C/p\u003E\n\u003Cp\u003EThe Root \u2192 Chain \u2192 Session hierarchy expresses those responsibilities at different security levels:\u003C/p\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Cstrong\u003ERoot\u003C/strong\u003E provides account-level authentication security.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003EChain\u003C/strong\u003E organizes related session continuity.\u003C/li\u003E\n\u003Cli\u003E\u003Cstrong\u003ESession\u003C/strong\u003E represents individual server-managed authentication state.\u003C/li\u003E\n\u003C/ul\u003E\n\u003Cp\u003EThis structure supports targeted session management without requiring all security operations to act on every session belonging to a user.\u003C/p\u003E\n\u003Cp\u003EAt the same time, UltimateAuth does not assume that every authentication mode requires identical server-side state.\u003C/p\u003E\n\u003Cp\u003EThe hierarchy is most directly relevant to session-managed authentication, while JWT-based modes preserve their own validation and lifecycle characteristics.\u003C/p\u003E\n\u003Cp\u003E\u003Cstrong\u003EAuthentication establishes trust. Session management determines how that trust is maintained, renewed, and invalidated over time.\u003C/strong\u003E\u003C/p\u003E\n\u003Ch2 class=\u0022mud-scrollspy-section\u0022 id=\u0022next-steps\u0022\u003ENext Steps\u003C/h2\u003E\n\u003Cul\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/sessions-devices/device-management\u0022\u003EDevice Management\u003C/a\u003E \u2014 Device context, chain association, and device-aware session management.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/security/session-security\u0022\u003ESession Security\u003C/a\u003E \u2014 Session expiration, rotation, revocation, and security controls.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/auth-modes\u0022\u003EAuthentication Modes\u003C/a\u003E \u2014 Understand how session behavior differs between modes.\u003C/li\u003E\n\u003Cli\u003E\u003Ca href=\u0022/docs/fundamentals/request-lifecycle\u0022\u003ERequest Lifecycle\u003C/a\u003E \u2014 Learn how protected requests validate authentication state.\u003C/li\u003E\n\u003C/ul\u003E\n", "Headings": [ { "Id": "understanding-the-session-hierarchy", @@ -159,6 +159,6 @@ "Level": 0 } ], - "SourceHash": "9E2453DEE6714F4FBD585903C857D8ED6CE4ED58E764E89762CC833DB7AC1B55", + "SourceHash": "73684F88B9CA0C26A096C11F9A771B1B040EB633E22FD7C5BA0BFEB48EB4F7E4", "BuilderVersion": "1" } \ No newline at end of file diff --git a/samples/CodeBeam.UltimateAuth.Sample.Shared.Hub/_Imports.razor b/samples/CodeBeam.UltimateAuth.Sample.Shared.Hub/_Imports.razor index 6785c741..300b3d2f 100644 --- a/samples/CodeBeam.UltimateAuth.Sample.Shared.Hub/_Imports.razor +++ b/samples/CodeBeam.UltimateAuth.Sample.Shared.Hub/_Imports.razor @@ -8,6 +8,7 @@ @using CodeBeam.UltimateAuth.Core.Contracts @using CodeBeam.UltimateAuth.Client @using CodeBeam.UltimateAuth.Client.Blazor +@using CodeBeam.UltimateAuth.Client.Abstractions @using CodeBeam.UltimateAuth.Client.Infrastructure @using CodeBeam.UltimateAuth.Client.Runtime @using CodeBeam.UltimateAuth.Client.Options diff --git a/samples/CodeBeam.UltimateAuth.Sample.Shared/Infrastructure/DarkModeManager.cs b/samples/CodeBeam.UltimateAuth.Sample.Shared/Infrastructure/DarkModeManager.cs index 7b81d010..2a80f190 100644 --- a/samples/CodeBeam.UltimateAuth.Sample.Shared/Infrastructure/DarkModeManager.cs +++ b/samples/CodeBeam.UltimateAuth.Sample.Shared/Infrastructure/DarkModeManager.cs @@ -1,5 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; namespace CodeBeam.UltimateAuth.Sample.Shared.Infrastructure; diff --git a/samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Program.cs b/samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Program.cs index b226287d..cd147780 100644 --- a/samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Program.cs +++ b/samples/UAuthHub/CodeBeam.UltimateAuth.Sample.UAuthHub/Program.cs @@ -29,7 +29,7 @@ builder.Services.AddScoped(); builder.Services.AddUltimateAuthServer(o => { - //o.GrantDelivery.Default = GrantDeliveryMode.Cookie; + o.Token.AccessTokenLifetime = TimeSpan.FromSeconds(30); o.Cryptography.JwtSigningKey = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("UltimateAuth-Development-JWT-Signing-Key-2026-Only")); o.Diagnostics.EnableRefreshDetails = true; diff --git a/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs b/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs index f55c591b..44402e02 100644 --- a/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs +++ b/samples/blazor-server/CodeBeam.UltimateAuth.Sample.BlazorServer/Program.cs @@ -12,6 +12,7 @@ using CodeBeam.UltimateAuth.Sample.Shared.ResourceApi; using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Users; +using Microsoft.Extensions.Options; using MudBlazor.Services; using MudExtensions.Services; using Scalar.AspNetCore; @@ -45,6 +46,9 @@ builder.Services.AddUltimateAuthServer(o => { + o.AuthMode = UAuthMode.Hybrid; + //o.Token.AccessTokenLifetime = TimeSpan.FromSeconds(30); + o.Diagnostics.EnableRefreshDetails = true; o.Login.MaxFailedAttempts = 2; o.Login.LockoutDuration = TimeSpan.FromSeconds(10); @@ -72,6 +76,11 @@ builder.Services.AddUltimateAuthClientBlazor(o => { + o.AutoRefresh.Background = false; + o.AutoRefresh.Proactive = true; + o.AutoRefresh.Reactive = false; + o.AutoRefresh.Interval = TimeSpan.FromSeconds(10); + o.Login.AllowCredentialPost = true; //o.AutoRefresh.Interval = TimeSpan.FromSeconds(5); o.Reauth.Behavior = ReauthBehavior.RaiseEvent; diff --git a/src/CodeBeam.UltimateAuth.Core/Defaults/UAuthConstants.cs b/src/CodeBeam.UltimateAuth.Core/Defaults/UAuthConstants.cs index 94521cb4..62ee961d 100644 --- a/src/CodeBeam.UltimateAuth.Core/Defaults/UAuthConstants.cs +++ b/src/CodeBeam.UltimateAuth.Core/Defaults/UAuthConstants.cs @@ -52,6 +52,7 @@ public static class Headers public const string Refresh = "X-UAuth-Refresh"; public const string AuthState = "X-UAuth-AuthState"; public const string DeviceType = "X-Device-Type"; + public const string AuthRecovery = "X-UAuth-Auth-Recovery"; } public static class Routes diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowEndpointFilter.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowEndpointFilter.cs index 2c6304d3..7553f772 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowEndpointFilter.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowEndpointFilter.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Http; +using CodeBeam.UltimateAuth.Core.Defaults; +using Microsoft.AspNetCore.Http; namespace CodeBeam.UltimateAuth.Server.Auth; @@ -13,12 +14,27 @@ public AuthFlowEndpointFilter(IAuthFlow authFlow) public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) { - var metadata = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata(); + var endpoint = context.HttpContext.GetEndpoint(); + + var metadata = endpoint?.Metadata.GetMetadata(); + + AuthFlowContext? flowContext = null; if (metadata != null) { - await _authFlow.BeginAsync(metadata.FlowType); + flowContext = await _authFlow.BeginAsync(metadata.FlowType); } + + var requiresAuthentication = endpoint?.Metadata + .GetMetadata() + is not null; + + if (requiresAuthentication && flowContext?.IsAuthenticated != true) + { + context.HttpContext.Response.Headers[UAuthConstants.Headers.AuthRecovery] = "challenge"; + return Results.Unauthorized(); + } + return await next(context); } } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Context/UAuthRequireAuthenticationMetadata.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Context/UAuthRequireAuthenticationMetadata.cs new file mode 100644 index 00000000..3a7e603e --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Context/UAuthRequireAuthenticationMetadata.cs @@ -0,0 +1,5 @@ +namespace CodeBeam.UltimateAuth.Server.Auth; + +internal sealed class UAuthRequireAuthenticationMetadata +{ +} diff --git a/src/CodeBeam.UltimateAuth.Server/Authorization/AspNetCore/UAuthStatusAuthorizationResultHandler.cs b/src/CodeBeam.UltimateAuth.Server/Authorization/AspNetCore/UAuthStatusAuthorizationResultHandler.cs index 3c8bb64c..8a79b227 100644 --- a/src/CodeBeam.UltimateAuth.Server/Authorization/AspNetCore/UAuthStatusAuthorizationResultHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Authorization/AspNetCore/UAuthStatusAuthorizationResultHandler.cs @@ -9,6 +9,7 @@ using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.ResourceApi; using CodeBeam.UltimateAuth.Server.Runtime; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization.Policy; using Microsoft.AspNetCore.Http; @@ -26,6 +27,27 @@ public async Task HandleAsync(RequestDelegate next, HttpContext context, Authori { if (!authorizeResult.Succeeded) { + if (authorizeResult.Challenged) + { + var isUAuthChallenge = + policy.AuthenticationSchemes.Count == 1 && + policy.AuthenticationSchemes.Contains(UAuthConstants.SchemeDefaults.GlobalScheme); + + if (policy.AuthenticationSchemes.Count == 0) + { + var schemes = context.RequestServices.GetRequiredService(); + + var scheme = await schemes.GetDefaultChallengeSchemeAsync(); + + isUAuthChallenge = scheme?.Name == UAuthConstants.SchemeDefaults.GlobalScheme; + } + + if (isUAuthChallenge) + { + context.Response.Headers[UAuthConstants.Headers.AuthRecovery] = "challenge"; + } + } + await _default.HandleAsync(next, context, policy, authorizeResult); return; } diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthEndpointRegistrar.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthEndpointRegistrar.cs index a99be842..0d6adaea 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthEndpointRegistrar.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthEndpointRegistrar.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; +using CodeBeam.UltimateAuth.Server.Extensions; namespace CodeBeam.UltimateAuth.Server.Endpoints; @@ -56,7 +57,7 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options //var user = group.MapGroup(""); var self = group.MapGroup("/me"); - var admin = group.MapGroup("/admin"); + var admin = group.MapGroup("/admin").RequireUAuthAuthentication(); if (options.Endpoints.Authentication != false) { @@ -150,23 +151,23 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options if (Enabled(UAuthActions.Sessions.ListChainsSelf)) selfSession.MapPost("/chains", async ([FromServices] ISessionEndpointHandler h, HttpContext ctx) - => await h.GetMyChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.QuerySession)).WithUAuthRateLimit(UAuthEndpoint.GetMyChains); + => await h.GetMyChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.QuerySession)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.GetMyChains); if (Enabled(UAuthActions.Sessions.GetChainSelf)) selfSession.MapPost("/chains/{chainId}", async ([FromServices] ISessionEndpointHandler h, SessionChainId chainId, HttpContext ctx) - => await h.GetMyChainDetailAsync(chainId, ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.QuerySession)).WithUAuthRateLimit(UAuthEndpoint.GetMyChainDetail); + => await h.GetMyChainDetailAsync(chainId, ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.QuerySession)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.GetMyChainDetail); if (Enabled(UAuthActions.Sessions.RevokeChainSelf)) selfSession.MapPost("/chains/{chainId}/revoke", async ([FromServices] ISessionEndpointHandler h, SessionChainId chainId, HttpContext ctx) - => await h.RevokeMyChainAsync(chainId, ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.RevokeMyChain); + => await h.RevokeMyChainAsync(chainId, ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.RevokeMyChain); if (Enabled(UAuthActions.Sessions.RevokeOtherChainsSelf)) selfSession.MapPost("/revoke-others",async ([FromServices] ISessionEndpointHandler h, HttpContext ctx) - => await h.RevokeOtherChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.RevokeOtherChains); + => await h.RevokeOtherChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.RevokeOtherChains); if (Enabled(UAuthActions.Sessions.RevokeAllChainsSelf)) selfSession.MapPost("/revoke-all", async ([FromServices] ISessionEndpointHandler h, HttpContext ctx) - => await h.RevokeAllMyChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.RevokeAllMyChains); + => await h.RevokeAllMyChainsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.RevokeSession), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.RevokeAllMyChains); @@ -218,11 +219,11 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options if (Enabled(UAuthActions.Users.ChangeStatusSelf)) self.MapPost("/status", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.ChangeStatusSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.ChangeStatusSelf); + => await h.ChangeStatusSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.ChangeStatusSelf); if (Enabled(UAuthActions.Users.DeleteSelf)) self.MapPost("/delete", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.DeleteMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.UserDeleteSelf); + => await h.DeleteMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.UserDeleteSelf); @@ -252,19 +253,19 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options { if (Enabled(UAuthActions.UserProfiles.GetSelf)) self.MapPost("/profile/get", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.GetMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement)).WithUAuthRateLimit(UAuthEndpoint.ProfileGetSelf); + => await h.GetMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.ProfileGetSelf); if (Enabled(UAuthActions.UserProfiles.CreateSelf)) self.MapPost("/profile/create", async (IUserEndpointHandler h, HttpContext ctx) - => await h.CreateProfileSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.CreateProfileSelf); + => await h.CreateProfileSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.CreateProfileSelf); if (Enabled(UAuthActions.UserProfiles.UpdateSelf)) self.MapPost("/profile/update", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.UpdateMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.ProfileUpdateSelf); + => await h.UpdateMeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.ProfileUpdateSelf); if (Enabled(UAuthActions.UserProfiles.DeleteSelf)) self.MapPost("/profile/delete", async (IUserEndpointHandler h, HttpContext ctx) - => await h.DeleteProfileSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.DeleteProfileSelf); + => await h.DeleteProfileSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserProfileManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.DeleteProfileSelf); @@ -290,31 +291,33 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options { if (Enabled(UAuthActions.UserIdentifiers.GetSelf)) self.MapPost("/identifiers/get", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.GetMyIdentifiersAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement)).WithUAuthRateLimit(UAuthEndpoint.GetMyIdentifiers); + => await h.GetMyIdentifiersAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement)) + .RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.GetMyIdentifiers); if (Enabled(UAuthActions.UserIdentifiers.AddSelf)) self.MapPost("/identifiers/add", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.AddUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.AddUserIdentifierSelf); + => await h.AddUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)) + .RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.AddUserIdentifierSelf); if (Enabled(UAuthActions.UserIdentifiers.UpdateSelf)) self.MapPost("/identifiers/update", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.UpdateUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.UpdateUserIdentifierSelf); + => await h.UpdateUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.UpdateUserIdentifierSelf); if (Enabled(UAuthActions.UserIdentifiers.SetPrimarySelf)) self.MapPost("/identifiers/set-primary",async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.SetPrimaryUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.SetPrimaryUserIdentifierSelf); + => await h.SetPrimaryUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.SetPrimaryUserIdentifierSelf); if (Enabled(UAuthActions.UserIdentifiers.UnsetPrimarySelf)) self.MapPost("/identifiers/unset-primary", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.UnsetPrimaryUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.UnsetPrimaryUserIdentifierSelf); + => await h.UnsetPrimaryUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.UnsetPrimaryUserIdentifierSelf); if (Enabled(UAuthActions.UserIdentifiers.VerifySelf)) self.MapPost("/identifiers/verify", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.VerifyUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.VerifyUserIdentifierSelf); + => await h.VerifyUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.VerifyUserIdentifierSelf); if (Enabled(UAuthActions.UserIdentifiers.DeleteSelf)) self.MapPost("/identifiers/delete", async ([FromServices] IUserEndpointHandler h, HttpContext ctx) - => await h.DeleteUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.DeleteUserIdentifierSelf); + => await h.DeleteUserIdentifierSelfAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.UserIdentifierManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.DeleteUserIdentifierSelf); @@ -363,15 +366,15 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options if (Enabled(UAuthActions.Credentials.AddSelf)) selfCredentials.MapPost("/add", async ([FromServices] ICredentialEndpointHandler h, HttpContext ctx) - => await h.AddAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.CredentialAddSelf); + => await h.AddAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.CredentialAddSelf); if (Enabled(UAuthActions.Credentials.ChangeSelf)) selfCredentials.MapPost("/change", async ([FromServices] ICredentialEndpointHandler h, HttpContext ctx) - => await h.ChangeSecretAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.CredentialChangeSelf); + => await h.ChangeSecretAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.CredentialChangeSelf); if (Enabled(UAuthActions.Credentials.RevokeSelf)) selfCredentials.MapPost("/revoke", async ([FromServices] ICredentialEndpointHandler h, HttpContext ctx) - => await h.RevokeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).WithUAuthRateLimit(UAuthEndpoint.CredentialRevokeSelf); + => await h.RevokeAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.CredentialManagement), new UAuthCsrfMetadata(UAuthCsrfOperation.AuthenticatedMutation)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.CredentialRevokeSelf); if (Enabled(UAuthActions.Credentials.BeginResetAnonymous)) @@ -416,15 +419,15 @@ public void MapEndpoints(RouteGroupBuilder rootGroup, UAuthServerOptions options // TODO: Add enabled actions here selfAuthz.MapPost("/check", async ([FromServices] IAuthorizationEndpointHandler h, HttpContext ctx) - => await h.CheckAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).WithUAuthRateLimit(UAuthEndpoint.AuthorizationCheck); + => await h.CheckAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.AuthorizationCheck); if (Enabled(UAuthActions.Authorization.Roles.GetSelf)) selfAuthz.MapPost("/roles/get", async ([FromServices] IAuthorizationEndpointHandler h, HttpContext ctx) - => await h.GetMyRolesAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).WithUAuthRateLimit(UAuthEndpoint.GetMyRoles); + => await h.GetMyRolesAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.GetMyRoles); if (Enabled(UAuthActions.Authorization.Permissions.GetSelf)) selfAuthz.MapPost("/permissions/get", async ([FromServices] IAuthorizationEndpointHandler h, HttpContext ctx) - => await h.GetMyPermissionsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).WithUAuthRateLimit(UAuthEndpoint.GetMyPermissions); + => await h.GetMyPermissionsAsync(ctx)).WithMetadata(new AuthFlowMetadata(AuthFlowType.AuthorizationManagement)).RequireUAuthAuthentication().WithUAuthRateLimit(UAuthEndpoint.GetMyPermissions); if (Enabled(UAuthActions.Authorization.Roles.GetAdmin)) diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs index ebcfa2d4..49bdf903 100644 --- a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs @@ -216,7 +216,13 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol services.AddScoped(); services.AddScoped(); - services.TryAddScoped(); + services.TryAddScoped(sp => + new CompositeSessionIdResolver( + sp.GetServices(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService(), + sp.GetRequiredService())); services.TryAddScoped(); services.TryAddScoped(); diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/UAuthEndpointConventionExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/UAuthEndpointConventionExtensions.cs new file mode 100644 index 00000000..81a11db9 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/UAuthEndpointConventionExtensions.cs @@ -0,0 +1,13 @@ +using CodeBeam.UltimateAuth.Server.Auth; +using Microsoft.AspNetCore.Builder; + +namespace CodeBeam.UltimateAuth.Server.Extensions; + +internal static class UAuthEndpointConventionExtensions +{ + public static TBuilder RequireUAuthAuthentication(this TBuilder builder) where TBuilder : IEndpointConventionBuilder + { + builder.WithMetadata(new UAuthRequireAuthenticationMetadata()); + return builder; + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/BearerSessionIdResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/BearerSessionIdResolver.cs index daa4862d..a248994b 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/BearerSessionIdResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/BearerSessionIdResolver.cs @@ -10,19 +10,29 @@ public sealed class BearerSessionIdResolver : IInnerSessionIdResolver public AuthSessionId? Resolve(HttpContext context) { var header = context.Request.Headers.Authorization.ToString(); + if (string.IsNullOrWhiteSpace(header)) return null; - if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + const string prefix = "Bearer "; + + if (!header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { return null; + } + + var raw = header[prefix.Length..].Trim(); - var raw = header["Bearer ".Length..].Trim(); if (string.IsNullOrWhiteSpace(raw)) return null; - if (!AuthSessionId.TryCreate(raw, out var sessionId)) + // UltimateAuth session IDs use Base64Url encoding. + // JWT access tokens are not session credentials. + if (raw.Contains('.')) return null; - return sessionId; + return AuthSessionId.TryCreate(raw, out var sessionId) + ? sessionId + : null; } } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/CompositeSessionIdResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/CompositeSessionIdResolver.cs index 019960a4..8609f540 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/CompositeSessionIdResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/CompositeSessionIdResolver.cs @@ -1,23 +1,32 @@ -using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core; +using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Options; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Options; namespace CodeBeam.UltimateAuth.Server.Infrastructure; -// TODO: Add policy and effective auth resolver. public sealed class CompositeSessionIdResolver : ISessionIdResolver { private readonly IReadOnlyDictionary _resolvers; private readonly IApplicationProfileReader _applicationProfileReader; private readonly IEffectiveServerOptionsProvider _effectiveOptionsProvider; + private readonly IAuthResponseResolver _authResponseResolver; + private readonly ITransportCredentialResolver _transportCredentialResolver; - public CompositeSessionIdResolver(IEnumerable resolvers, IApplicationProfileReader applicationProfileReader, IEffectiveServerOptionsProvider effectiveOptionsProvider) + internal CompositeSessionIdResolver( + IEnumerable resolvers, + IApplicationProfileReader applicationProfileReader, + IEffectiveServerOptionsProvider effectiveOptionsProvider, + IAuthResponseResolver authResponseResolver, + ITransportCredentialResolver transportCredentialResolver) { _resolvers = resolvers.ToDictionary(r => r.Name, StringComparer.OrdinalIgnoreCase); + _applicationProfileReader = applicationProfileReader; _effectiveOptionsProvider = effectiveOptionsProvider; + _authResponseResolver = authResponseResolver; + _transportCredentialResolver = transportCredentialResolver; } public async ValueTask ResolveAsync(HttpContext context, CancellationToken ct = default) @@ -25,7 +34,20 @@ public CompositeSessionIdResolver(IEnumerable resolvers ct.ThrowIfCancellationRequested(); var applicationProfile = await _applicationProfileReader.ReadAsync(context); + var effective = _effectiveOptionsProvider.GetEffective(context, applicationProfile); + + if (effective.Mode == UAuthMode.Hybrid) + { + var response = _authResponseResolver.ResolveForAuthentication(effective.Mode, applicationProfile, effective); + var credential = await _transportCredentialResolver.ResolveAsync(context, effective.Mode, response); + + if (credential is null) + return null; + + return AuthSessionId.TryCreate(credential.Value, out var sessionId) ? sessionId : null; + } + var options = effective.Options.SessionResolution; foreach (var name in options.Order) diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs index 5730707d..ae71315b 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs @@ -57,8 +57,6 @@ private static void ApplyHybridDefaults(UAuthServerOptions options) token.IssueJwt = true; token.IssueOpaque = true; - token.AccessTokenLifetime = TimeSpan.FromMinutes(10); - token.RefreshTokenLifetime = TimeSpan.FromDays(7); cookie.Session.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); @@ -76,12 +74,9 @@ private static void ApplySemiHybridDefaults(UAuthServerOptions options) token.IssueJwt = true; token.IssueOpaque = true; - token.AccessTokenLifetime = TimeSpan.FromMinutes(10); - token.RefreshTokenLifetime = TimeSpan.FromDays(7); token.AddJwtIdClaim = true; cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); - cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } @@ -100,8 +95,6 @@ private static void ApplyPureJwtDefaults(UAuthServerOptions options) token.IssueJwt = true; token.IssueOpaque = false; token.IssueRefresh = true; - token.AccessTokenLifetime = TimeSpan.FromMinutes(10); - token.RefreshTokenLifetime = TimeSpan.FromDays(7); token.AddJwtIdClaim = true; cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs index 21816066..3e016a26 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs @@ -25,6 +25,7 @@ public void Configure(CorsOptions options) var exposedHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { "X-UAuth-Refresh", + "X-UAuth-Auth-Recovery", "X-UAuth-Access-Header", "X-UAuth-Access-Expires", "X-UAuth-Access-Format", diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthCorsOptionsSetup.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceCorsOptionsSetup.cs similarity index 75% rename from src/CodeBeam.UltimateAuth.Server/Options/UAuthCorsOptionsSetup.cs rename to src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceCorsOptionsSetup.cs index 07cff978..7962eccb 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthCorsOptionsSetup.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceCorsOptionsSetup.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Server.Options; -using Microsoft.AspNetCore.Cors.Infrastructure; +using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.Extensions.Options; namespace CodeBeam.UltimateAuth.Server.Options; @@ -19,7 +18,10 @@ public void Configure(CorsOptions options) .WithOrigins(cors.AllowedOrigins.ToArray()) .AllowAnyHeader() .AllowAnyMethod() - .AllowCredentials(); + .AllowCredentials() + .WithExposedHeaders( + "X-UAuth-Auth-Recovery", + "Retry-After"); }); } } diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Components/UAuthLoginForm.razor.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Components/UAuthLoginForm.razor.cs index 0dd5a45a..491cea1a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Components/UAuthLoginForm.razor.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Components/UAuthLoginForm.razor.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Device/BrowserDeviceIdStorage.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Device/BrowserDeviceIdStorage.cs index 1ef3de09..7e1ed73e 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Device/BrowserDeviceIdStorage.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Device/BrowserDeviceIdStorage.cs @@ -1,8 +1,6 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Device; -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Abstractions; -namespace CodeBeam.UltimateAuth.Client.Blazor.Device; +namespace CodeBeam.UltimateAuth.Client.Blazor; /// /// Represents a device ID storage implementation that uses browser client storage to persist the device ID. diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Extensions/ServiceCollectionExtensions.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Extensions/ServiceCollectionExtensions.cs index acf912fa..87d63835 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Extensions/ServiceCollectionExtensions.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Extensions/ServiceCollectionExtensions.cs @@ -1,7 +1,5 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Blazor.Device; using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -using CodeBeam.UltimateAuth.Client.Device; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Extensions; using CodeBeam.UltimateAuth.Client.Infrastructure; @@ -39,13 +37,16 @@ public static IServiceCollection AddUltimateAuthClientBlazor(this IServiceCollec /// private static IServiceCollection AddUltimateAuthClientBlazorInternal(this IServiceCollection services) { - services.TryAddScoped(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); - services.AddScoped(); services.AddScoped(); services.TryAddScoped(); diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/BrowserClientStorage.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/BrowserClientStorage.cs index 0ea7ac51..4f5e4e9e 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/BrowserClientStorage.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/BrowserClientStorage.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Abstractions; using Microsoft.JSInterop; namespace CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/SessionCoordinator.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/SessionCoordinator.cs index 96469232..61952b2b 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/SessionCoordinator.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/SessionCoordinator.cs @@ -1,123 +1,496 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -// TODO: Add multi tab single refresh support +// TODO: Add multi-tab single refresh support. internal sealed class SessionCoordinator : ISessionCoordinator { + private static readonly TimeSpan ScheduleCheckInterval = TimeSpan.FromSeconds(1); + private readonly IUAuthClient _client; + private readonly IUAuthTokenStore _tokenStore; private readonly NavigationManager _navigation; private readonly UAuthClientOptions _options; private readonly UAuthClientDiagnostics _diagnostics; + private readonly UAuthRefreshSchedule _refreshSchedule; + private readonly IUAuthRefreshCoordinator _refreshCoordinator; private readonly IClock _clock; + private readonly ILogger _logger; - private CancellationTokenSource? _cts; + private readonly object _lifecycleSync = new(); + private BackgroundRun? _run; + private bool _disposed; private DateTimeOffset _refreshNotBefore; + private long? _refreshNotBeforeEpoch; public event Action? ReauthRequired; - public SessionCoordinator(IUAuthClient client, NavigationManager navigation, IOptions options, UAuthClientDiagnostics diagnostics, IClock clock) + public SessionCoordinator( + IUAuthClient client, + NavigationManager navigation, + IOptions options, + UAuthClientDiagnostics diagnostics, + UAuthRefreshSchedule refreshSchedule, + IUAuthRefreshCoordinator refreshCoordinator, + IClock clock, + IUAuthTokenStore tokenStore, + ILogger logger) { _client = client; _navigation = navigation; _options = options.Value; _diagnostics = diagnostics; + _refreshSchedule = refreshSchedule; + _refreshCoordinator = refreshCoordinator; _clock = clock; + _tokenStore = tokenStore; + _logger = logger; } - public async Task StartAsync(CancellationToken cancellationToken = default) + private TimeSpan Interval => _options.AutoRefresh.Interval ?? TimeSpan.FromMinutes(5); + + public async Task StartAsync(CancellationToken ct = default) { - if (!_options.AutoRefresh.Enabled) - return; + while (true) + { + BackgroundRun? created = null; + Task? previousCompletion = null; - if (_cts is not null) - return; + lock (_lifecycleSync) + { + ObjectDisposedException.ThrowIf( + _disposed, + this); + + if (!_options.AutoRefresh.Background) + { + return; + } + + ct.ThrowIfCancellationRequested(); + + if (_run is not null) + { + if (!_run.StopRequested && + !_run.Source.IsCancellationRequested) + { + return; + } + + previousCompletion = _run.Completion.Task; + } + else + { + created = new BackgroundRun(ct); - _diagnostics.MarkStarted(); - _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + _run = created; - _ = RunAsync(_cts.Token); + ResetRefreshBackoff(); + + _diagnostics.MarkStarted(); + } + } + + if (created is not null) + { + _ = RunAsync(created); + + return; + } + + await previousCompletion!.WaitAsync(ct); + } } - private async Task RunAsync(CancellationToken ct) + private async Task RunAsync(BackgroundRun run) { - var interval = _options.AutoRefresh.Interval ?? TimeSpan.FromMinutes(5); + var ct = run.Source.Token; try { - while (!ct.IsCancellationRequested) + while (!ct.IsCancellationRequested && + IsCurrentRun(run)) { - var delay = _refreshNotBefore - _clock.UtcNow; - if (delay < interval) delay = interval; - _diagnostics.SetNextAutomaticRefresh(UAuthRateLimit.NotBefore(_clock.UtcNow, delay)); - // Chunk very long guidance to stay within native timer bounds; TickAsync still checks the deadline. - await Task.Delay(delay > TimeSpan.FromDays(1) ? TimeSpan.FromDays(1) : delay, ct); + var now = _clock.UtcNow; + + var snapshot = _tokenStore.Capture(); + + var notBefore = + GetRefreshNotBefore(snapshot); + + var next = + _refreshSchedule.GetNextRefreshAt(snapshot); + + if (next is null) + { + _diagnostics.SetNextAutomaticRefresh(null); + + await Task.Delay( + ScheduleCheckInterval, + ct); + + continue; + } + + var scheduledAt = next.Value > notBefore + ? next.Value + : notBefore; + + _diagnostics.SetNextAutomaticRefresh( + scheduledAt); + + var delay = scheduledAt - now; + + if (delay > TimeSpan.Zero) + { + await Task.Delay( + delay > ScheduleCheckInterval + ? ScheduleCheckInterval + : delay, + ct); + + continue; + } + + ct.ThrowIfCancellationRequested(); + + if (!IsCurrentRun(run)) + { + return; + } + + if (!_refreshSchedule.IsDue(snapshot)) + { + continue; + } + _diagnostics.SetNextAutomaticRefresh(null); - await TickAsync(); - if (_diagnostics.IsTerminated) + try + { + await TickCoreAsync(ct); + } + catch (OperationCanceledException) + when (ct.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + _logger.LogWarning( + ex, + "Background authentication refresh failed."); + } + + if (ct.IsCancellationRequested || + !IsCurrentRun(run) || + _diagnostics.IsTerminated) + { return; + } + + var current = _tokenStore.Capture(); + + if (current.Epoch != snapshot.Epoch) + { + continue; + } + + if (_refreshSchedule.IsDue(current)) + { + DeferRefresh( + current, + _refreshSchedule.GetRetryAt(current)); + } } } catch (OperationCanceledException) + when (ct.IsCancellationRequested) { // Normal coordinator shutdown. } + catch (Exception ex) + { + _logger.LogError( + ex, + "Background authentication coordinator terminated unexpectedly."); + } finally { - _diagnostics.SetNextAutomaticRefresh(null); + await CompleteRunAsync(run); } } public Task StopAsync() { - _diagnostics.MarkStopped(); - _cts?.Cancel(); - return Task.CompletedTask; + return StopCoreAsync(disposing: false); + } + + public ValueTask DisposeAsync() + { + return new ValueTask( + StopCoreAsync(disposing: true)); } - public async ValueTask DisposeAsync() + private async Task StopCoreAsync(bool disposing) { - await StopAsync(); + BackgroundRun? run; + bool requestCancellation = false; + + lock (_lifecycleSync) + { + if (disposing) + { + _disposed = true; + } + + run = _run; + + if (run is null) + { + return; + } + + if (!run.StopRequested) + { + run.StopRequested = true; + + requestCancellation = true; + + _diagnostics.MarkStopped(); + } + } + + if (requestCancellation) + { + try + { + run.Source.Cancel(); + } + finally + { + run.CancellationCompleted.TrySetResult(true); + } + } + + await run.Completion.Task; } - internal async Task TickAsync() + internal Task TickAsync(CancellationToken ct = default) { - if (_clock.UtcNow < _refreshNotBefore) return; - _diagnostics.MarkAutomaticRefresh(); + ThrowIfDisposed(); + + return TickCoreAsync(ct); + } + + private async Task TickCoreAsync(CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + + if (!_options.AutoRefresh.Background) + { + return; + } + + var expected = _tokenStore.Capture(); + + var now = _clock.UtcNow; + + if (now < GetRefreshNotBefore(expected)) + { + return; + } + + if (!_refreshSchedule.IsDue(expected)) + { + return; + } + + var result = await _refreshCoordinator.RefreshIfCurrentAsync(UAuthRefreshTrigger.Background, expected, ct); + + if (ct.IsCancellationRequested) + { + return; + } + + var current = _tokenStore.Capture(); + + if (result.Outcome == RefreshOutcome.ReauthRequired) + { + var clearedEpoch = unchecked( + expected.Epoch + 1); - var result = await _client.Flows.RefreshAsync(true); + if (current.Epoch != clearedEpoch || + current.Token is not null) + { + return; + } + } + else if (current.Epoch != expected.Epoch) + { + return; + } if (result.Status == 429) { - _refreshNotBefore = UAuthRateLimit.NotBefore(_clock.UtcNow, result.RetryAfter); + DeferRefresh( + expected, + UAuthRateLimit.NotBefore( + _clock.UtcNow, + result.RetryAfter)); + return; } if (result.Outcome != RefreshOutcome.ReauthRequired) + { return; + } - if (result.Outcome == RefreshOutcome.ReauthRequired) + _diagnostics.MarkTerminated(CoordinatorTerminationReason.ReauthRequired); + + switch (_options.Reauth.Behavior) + { + case ReauthBehavior.Redirect: + _navigation.NavigateTo(_options.Reauth.RedirectPath ?? _options.Endpoints.Login, forceLoad: true); + break; + + case ReauthBehavior.RaiseEvent: + + ReauthRequired?.Invoke(); + + break; + } + } + + private bool IsCurrentRun(BackgroundRun run) + { + lock (_lifecycleSync) + { + return ReferenceEquals(_run, run) && !run.StopRequested && !_disposed; + } + } + + private void ThrowIfDisposed() + { + lock (_lifecycleSync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + } + } + + private void ResetRefreshBackoff() + { + _refreshNotBefore = default; + _refreshNotBeforeEpoch = null; + } + + private DateTimeOffset GetRefreshNotBefore(UAuthTokenSnapshot snapshot) + { + if (_refreshNotBeforeEpoch != snapshot.Epoch) + { + ResetRefreshBackoff(); + } + + return _refreshNotBefore; + } + + private void DeferRefresh(UAuthTokenSnapshot expected, DateTimeOffset notBefore) + { + var current = _tokenStore.Capture(); + + if (current.Epoch != expected.Epoch) { - switch (_options.Reauth.Behavior) + return; + } + + if (_refreshNotBeforeEpoch != expected.Epoch) + { + _refreshNotBeforeEpoch = expected.Epoch; + _refreshNotBefore = notBefore; + + return; + } + + if (notBefore > _refreshNotBefore) + { + _refreshNotBefore = notBefore; + } + } + + private async Task CompleteRunAsync(BackgroundRun run) + { + Task? cancellationCompletion = null; + + lock (_lifecycleSync) + { + if (run.StopRequested) + { + cancellationCompletion = + run.CancellationCompleted.Task; + } + else + { + CompleteRunUnderLock(run); + + return; + } + } + + await cancellationCompletion; + + lock (_lifecycleSync) + { + CompleteRunUnderLock(run); + } + } + + private void CompleteRunUnderLock(BackgroundRun run) + { + try + { + if (ReferenceEquals(_run, run)) { - case ReauthBehavior.Redirect: _navigation.NavigateTo(_options.Reauth.RedirectPath ?? _options.Endpoints.Login, forceLoad: true); - break; + _diagnostics.SetNextAutomaticRefresh(null); - case ReauthBehavior.RaiseEvent: - ReauthRequired?.Invoke(); - break; + _diagnostics.MarkStopped(); + + _run = null; } - _diagnostics.MarkTerminated(CoordinatorTerminationReason.ReauthRequired); + run.Source.Dispose(); + } + finally + { + run.Completion.TrySetResult(true); + } + } + + private sealed class BackgroundRun + { + public CancellationTokenSource Source { get; } + + public TaskCompletionSource Completion { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource CancellationCompleted { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool StopRequested { get; set; } + + public BackgroundRun(CancellationToken cancellationToken) + { + Source = CancellationTokenSource + .CreateLinkedTokenSource(cancellationToken); } } } diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRecoveringRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRecoveringRequestClient.cs new file mode 100644 index 00000000..e78ca9d8 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRecoveringRequestClient.cs @@ -0,0 +1,148 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Options; +using Microsoft.Extensions.Options; + +namespace CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; + +internal sealed class UAuthRecoveringRequestClient : IUAuthRequestClient +{ + private readonly UAuthRequestClient _raw; + private readonly IUAuthRequestRecovery _recovery; + private readonly IUAuthTokenStore _tokenStore; + private readonly UAuthClientAutoRefreshOptions _options; + + public UAuthRecoveringRequestClient( + UAuthRequestClient raw, + IUAuthRequestRecovery recovery, + IUAuthTokenStore tokenStore, + IOptions options) + { + _raw = raw; + _recovery = recovery; + _tokenStore = tokenStore; + _options = options.Value.AutoRefresh; + } + + public Task NavigateAsync(string endpoint, IDictionary? form = null, CancellationToken ct = default) + => _raw.NavigateAsync(endpoint, form, ct); + + public Task SendFormAsync(string endpoint, IDictionary? form = null, CancellationToken ct = default) + => _raw.SendFormAsync(endpoint, form, ct); + + public Task SendFormAsync(string endpoint, IDictionary? form, bool navigateOnSuccess, CancellationToken ct = default) + => _raw.SendFormAsync(endpoint, form, navigateOnSuccess, ct); + + public Task SendFormAsync(string endpoint, IDictionary? form, string? accessToken, CancellationToken ct = default) + => _raw.SendFormAsync(endpoint, form, accessToken, ct); + + public Task SendJsonAsync(string endpoint, object? payload = null, CancellationToken ct = default) + => _raw.SendJsonAsync(endpoint, payload, ct); + + + public async Task SendJsonAsync( + string endpoint, + object? payload, + UAuthRequestAuthentication authentication, + CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + + if (authentication == UAuthRequestAuthentication.None) + { + return await _raw.SendJsonAsync(endpoint, payload, ct); + } + + if (authentication is not UAuthRequestAuthentication.Recoverable) + { + throw new ArgumentOutOfRangeException(nameof(authentication)); + } + + var preparation = await _recovery.PrepareAsync(ct); + + if (!preparation.CanProceed) + { + return FromPreparationFailure(preparation.Failure!); + } + + var snapshot = preparation.Snapshot; + + var first = await _raw.SendJsonRawAsync( + endpoint, + payload, + snapshot, + ct); + + if (!_options.Reactive || !first.CanRecoverAuthentication) + { + return first; + } + + if (_tokenStore.Capture().Epoch != snapshot.Epoch) + { + return first; + } + + var refreshed = await _recovery.RecoverAsync(snapshot, ct); + + if (refreshed is null) + { + return first; + } + + ct.ThrowIfCancellationRequested(); + + var current = _tokenStore.Capture(); + + if (current.Epoch != snapshot.Epoch || + current.Generation != refreshed.Generation || + current.Generation == snapshot.Generation || + current.Token is null || + current.Token.IsExpired(DateTimeOffset.UtcNow) || + string.Equals( + current.Token.Token, + snapshot.Token?.Token, + StringComparison.Ordinal)) + { + return first; + } + + // Replay exactly once, with final credential validation + // performed after transport bootstrap. + return await _raw.SendJsonRawAsync( + endpoint, + payload, + refreshed, + ct, + replayOf: first, + rejectedSnapshot: snapshot); + } + + + public Task TryAndCommitAsync(string tryEndpoint, string commitEndpoint, object request, CancellationToken ct = default) + => _raw.TryAndCommitAsync(tryEndpoint, commitEndpoint, request, ct); + + public Task GetLoginTransportAsync(string endpoint, CancellationToken ct = default) + => _raw.GetLoginTransportAsync(endpoint, ct); + + public Task NavigateToUrlAsync(string url, CancellationToken ct = default) + => _raw.NavigateToUrlAsync(url, ct); + + public Task NavigateToPkceReturnUrlAsync(string redirectUrl, string expectedReturnUrl, CancellationToken ct = default) + => _raw.NavigateToPkceReturnUrlAsync(redirectUrl, expectedReturnUrl, ct); + + + private static UAuthTransportResult FromPreparationFailure(RefreshResult failure) + { + return new UAuthTransportResult + { + Ok = false, + Status = failure.Status >= 400 + ? failure.Status + : 401, + + RetryAfter = failure.RetryAfter is { } retryAfter + ? Math.Ceiling(retryAfter.TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture) + : null + }; + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRefreshTransport.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRefreshTransport.cs new file mode 100644 index 00000000..d926cfde --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRefreshTransport.cs @@ -0,0 +1,24 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using Microsoft.Extensions.Options; + +namespace CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; + +internal sealed class UAuthRefreshTransport : IUAuthRefreshTransport +{ + private readonly UAuthRequestClient _raw; + private readonly UAuthClientOptions _options; + + public UAuthRefreshTransport(UAuthRequestClient raw, IOptions options) + { + _raw = raw; + _options = options.Value; + } + + public Task SendAsync(CancellationToken ct = default) + { + var url = UAuthUrlBuilder.Build(_options.Endpoints.BasePath, _options.Endpoints.Refresh, _options.MultiTenant); + return _raw.SendFormAsync(url, form: null, ct: ct); + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRequestClient.cs index 730b2b15..bf16be9a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRequestClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthRequestClient.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -105,12 +104,72 @@ public async Task SendFormAsync(string endpoint, IDictiona return result; } - public async Task SendJsonAsync(string endpoint, object? payload = default, CancellationToken ct = default) + + public Task SendJsonAsync(string endpoint, object? payload = default, CancellationToken ct = default) + { + return SendJsonRawAsync(endpoint, payload, _tokenStore.Capture(), ct); + } + internal async Task SendJsonRawAsync( + string endpoint, + object? payload, + UAuthTokenSnapshot snapshot, + CancellationToken ct = default, + UAuthTransportResult? replayOf = null, + UAuthTokenSnapshot? rejectedSnapshot = null) { ct.ThrowIfCancellationRequested(); await _bootstrapper.EnsureStartedAsync(ct); + ct.ThrowIfCancellationRequested(); + + var current = _tokenStore.Capture(); + + if (current.Epoch != snapshot.Epoch) + { + if (replayOf is not null) + { + return replayOf; + } + + throw new OperationCanceledException( + "Authentication state changed before request execution."); + } + + var token = snapshot.Token; + + if (replayOf is not null) + { + // A replay must use a valid credential from the + // same authentication lifecycle. + token = current.Token; + + if (rejectedSnapshot is null || + current.Epoch != rejectedSnapshot.Epoch || + current.Generation == rejectedSnapshot.Generation || + token is null || + token.IsExpired(DateTimeOffset.UtcNow) || + string.Equals( + token.Token, + rejectedSnapshot.Token?.Token, + StringComparison.Ordinal)) + { + return replayOf; + } + } + + var accessToken = token is not null && + !token.IsExpired(DateTimeOffset.UtcNow) + ? token.Token + : null; + + // Never downgrade an authenticated replay to a + // cookie-only or anonymous request. + if (replayOf is not null && accessToken is null) + { + return replayOf; + } + var result = await InvokeAsync( "uauth.postJson", ct, @@ -118,16 +177,22 @@ public async Task SendJsonAsync(string endpoint, object? p { url = endpoint, payload, - accessToken = GetAccessToken(), - applicationProfile = _options.ApplicationProfile.ToString(), + accessToken, + applicationProfile = + _options.ApplicationProfile.ToString(), trustedOrigin = ResolveTrustedOrigin() }); if (result is null) - throw new UAuthProtocolException("Invalid error response format."); + { + throw new UAuthProtocolException( + "Invalid error response format."); + } if (result.Status == 0) + { throw new UAuthTransportException("Network error."); + } return result; } @@ -246,7 +311,6 @@ target.Scheme is not ("https" or "http") || if (token.IsExpired(DateTimeOffset.UtcNow)) { - _tokenStore.Clear(); return null; } diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs index ddb22b6a..249e8580 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/UAuthResourceRequestClient.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -13,70 +12,180 @@ internal sealed class UAuthResourceRequestClient : IUAuthResourceRequestClient private readonly IJSRuntime _js; private readonly IUAuthClientBootstrapper _bootstrapper; private readonly IUAuthTokenStore _tokenStore; + private readonly IUAuthRequestRecovery _recovery; private readonly UAuthClientOptions _options; - public UAuthResourceRequestClient(IJSRuntime js, IUAuthClientBootstrapper bootstrapper, IUAuthTokenStore tokenStore, IOptions options) + public UAuthResourceRequestClient(IJSRuntime js, IUAuthClientBootstrapper bootstrapper, IUAuthTokenStore tokenStore, IUAuthRequestRecovery recovery, IOptions options) { _js = js; _bootstrapper = bootstrapper; _tokenStore = tokenStore; + _recovery = recovery; _options = options.Value; } - public async Task SendAsync(string method, string endpoint, object? payload = null, CancellationToken ct = default) + public async Task SendAsync( + string method, + string endpoint, + object? payload = null, + CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - await _bootstrapper.EnsureStartedAsync(); + var preparation = await _recovery.PrepareAsync(ct); - ct.ThrowIfCancellationRequested(); + if (!preparation.CanProceed) + { + return FromPreparationFailure(preparation.Failure!); + } - var requestId = Guid.NewGuid().ToString("N"); + var (first, sentSnapshot) = await SendRawAsync( + method, + endpoint, + payload, + preparation.Snapshot, + ct); - using var registration = ct.Register(() => + if (!_options.AutoRefresh.Reactive || + !first.CanRecoverAuthentication) { - _ = CancelRequestAsync(requestId); - }); + return first; + } - try + if (_tokenStore.Capture().Epoch != sentSnapshot.Epoch) { - var accessToken = _tokenStore.Read(); + return first; + } - if (accessToken is not null && accessToken.IsExpired(DateTimeOffset.UtcNow)) - { - _tokenStore.Clear(); - accessToken = null; - } + var refreshed = await _recovery.RecoverAsync( + sentSnapshot, + ct); + + if (refreshed is null) + { + return first; + } + + ct.ThrowIfCancellationRequested(); + + var current = _tokenStore.Capture(); + + if (current.Epoch != sentSnapshot.Epoch || + current.Generation != refreshed.Generation || + current.Generation == sentSnapshot.Generation || + current.Token is null || + current.Token.IsExpired(DateTimeOffset.UtcNow) || + string.Equals( + current.Token.Token, + sentSnapshot.Token?.Token, + StringComparison.Ordinal)) + { + return first; + } + + var (replay, _) = await SendRawAsync( + method, + endpoint, + payload, + refreshed, + ct, + replayOf: first, + rejectedSnapshot: sentSnapshot); + + return replay; + } + + private async Task<(UAuthResourceTransportResult Response, UAuthTokenSnapshot SentSnapshot)> SendRawAsync( + string method, + string endpoint, + object? payload, + UAuthTokenSnapshot snapshot, + CancellationToken ct, + UAuthResourceTransportResult? replayOf = null, + UAuthTokenSnapshot? rejectedSnapshot = null) + { + ct.ThrowIfCancellationRequested(); + + await _bootstrapper.EnsureStartedAsync(ct); + + ct.ThrowIfCancellationRequested(); + + var current = _tokenStore.Capture(); - var result = await _js.InvokeAsync("uauth.resourceRequest", ct, - new + if (current.Epoch != snapshot.Epoch) + { + return ( + replayOf ?? new UAuthResourceTransportResult { - url = endpoint, - baseAddress = _options.Resource.BaseAddress, - method, - payload, - applicationProfile = _options.ApplicationProfile.ToString(), - credentials = _options.Resource.Credentials.ToString(), - accessToken = accessToken?.Token, - requestId - }); - - if (result is null) - { - throw new UAuthProtocolException("Invalid Resource API transport response."); - } + Ok = false, + Status = 401 + }, + snapshot); + } + + // Use the latest credential within the same + // authentication lifecycle. + snapshot = current; + + var token = snapshot.Token; + + if (token is not null && + token.IsExpired(DateTimeOffset.UtcNow)) + { + token = null; + } + + // Replay must never fall back to an anonymous or + // cookie-only request, or reuse the rejected credential. + if (replayOf is not null && + (token is null || + rejectedSnapshot is null || + snapshot.Generation == rejectedSnapshot.Generation || + string.Equals( + token.Token, + rejectedSnapshot.Token?.Token, + StringComparison.Ordinal))) + { + return (replayOf, snapshot); + } + + var requestId = Guid.NewGuid().ToString("N"); - if (result.Status == 0) + using var registration = ct.Register(() => + { + _ = CancelRequestAsync(requestId); + }); + + var result = await _js.InvokeAsync( + "uauth.resourceRequest", + ct, + new { - throw new UAuthTransportException("Resource API network error."); - } + url = endpoint, + baseAddress = _options.Resource.BaseAddress, + method, + payload, + applicationProfile = + _options.ApplicationProfile.ToString(), + credentials = + _options.Resource.Credentials.ToString(), + accessToken = token?.Token, + requestId + }); - return result; + if (result is null) + { + throw new UAuthProtocolException( + "Invalid Resource API transport response."); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) + + if (result.Status == 0) { - throw; + throw new UAuthTransportException( + "Resource API network error."); } + + return (result, snapshot); } private async Task CancelRequestAsync(string requestId) @@ -94,4 +203,22 @@ private async Task CancelRequestAsync(string requestId) // Cancellation is best-effort. } } + + private static UAuthResourceTransportResult FromPreparationFailure( + RefreshResult failure) + { + return new UAuthResourceTransportResult + { + Ok = false, + Status = failure.Status >= 400 + ? failure.Status + : 401, + + RetryAfter = failure.RetryAfter is { } retryAfter + ? Math.Ceiling(retryAfter.TotalSeconds) + .ToString( + System.Globalization.CultureInfo.InvariantCulture) + : null + }; + } } diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/WebClientDeviceProvider.cs b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/WebClientDeviceProvider.cs index 3cc98210..a90b9cd8 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/WebClientDeviceProvider.cs +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/Infrastructure/WebClientDeviceProvider.cs @@ -4,7 +4,7 @@ using CodeBeam.UltimateAuth.Core.Domain; using Microsoft.JSInterop; -namespace CodeBeam.UltimateAuth.Client.Blazor; +namespace CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; internal sealed class WebClientDeviceProvider : IClientDeviceProvider { diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js b/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js index 56a8700d..b0e443f0 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/TScripts/uauth.js @@ -477,6 +477,7 @@ window.uauth.request = async function (options) { ok: response.ok, status: response.status, refreshOutcome: response.headers.get("X-UAuth-Refresh"), + authRecovery: response.headers.get("X-UAuth-Auth-Recovery"), accessToken: responseAccessToken, accessTokenExpiresAt, accessTokenFormat, @@ -637,6 +638,7 @@ window.uauth.resourceRequest = async function (options) { return { retryAfter: response.headers.get("Retry-After"), + authRecovery: response.headers.get("X-UAuth-Auth-Recovery"), ok: response.ok, status: response.status, body: responseBody, diff --git a/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js b/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js index 4390e819..327127e0 100644 --- a/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js +++ b/src/client/CodeBeam.UltimateAuth.Client.Blazor/wwwroot/uauth.min.js @@ -1 +1 @@ -window.uauth=window.uauth||{};window.uauth.storage={set:function(n,t,i){const r=n==="local"?window.localStorage:window.sessionStorage;r.setItem(t,i)},get:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)},remove:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;i.removeItem(t)},exists:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)!==null}};window.uauth.submitForm=async function(n,t=null){if(!n)return;if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const r=window.uauth.validateAuthUrl(n.action,t);n.action=r;let i=n.querySelector("input[name='__uauth_device']");i||(i=document.createElement("input"),i.type="hidden",i.name="__uauth_device",n.appendChild(i));i.value=window.uauth.deviceId;await window.uauth.antiforgery.appendToForm(n,t);n.submit()};window.uauth.tryAndCommit=async function(n){const{tryUrl:c,commitUrl:l,data:e,applicationProfile:o,trustedOrigin:u}=n,a=window.uauth.validateAuthUrl(c,u),v=window.uauth.validateAuthUrl(l,u),s=window.uauth.deviceId;if(!s)throw new Error("UAuth deviceId is not initialized.");const r=await window.uauth.postJson({url:a,payload:e,applicationProfile:o,trustedOrigin:u});if(!r||!Number.isInteger(r.status))throw new Error("Invalid UAuth transport response.");const i=r.status;if(i===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:r.retryAfter??null};const y=i>=200&&i<300,h=i>=400&&i<500;if(!y&&!h)throw new Error(`Unexpected UAuth try response: HTTP ${i}.`);const t=r.body;if(!t||typeof t!="object"||Array.isArray(t)||typeof t.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(h&&t.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");const f={isSuccess:t.isSuccess,reason:t.reason??null,remainingAttempts:t.remainingAttempts??null,lockoutUntilUtc:t.lockoutUntilUtc??null,requiresMfa:t.requiresMfa??!1,retryWithNewPkce:t.retryWithNewPkce??!1,previewReceipt:t.previewReceipt??null};if(f.isSuccess){const n=document.createElement("form");n.method="POST";n.action=v;for(const t of Object.keys(e)){const i=document.createElement("input");i.type="hidden";i.name=t;i.value=e[t]??"";n.appendChild(i)}if(f.previewReceipt){const t=document.createElement("input");t.type="hidden";t.name="PreviewReceipt";t.value=f.previewReceipt;n.appendChild(t)}const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=o??"";n.appendChild(t);const i=document.createElement("input");i.type="hidden";i.name="__uauth_device";i.value=s;n.appendChild(i);document.body.appendChild(n);try{await window.uauth.submitForm(n,u)}catch(r){n.remove();throw r;}}return f};window.uauth.post=async function(n){const{url:e,mode:t,data:i,applicationProfile:u,trustedOrigin:r,accessToken:o=null}=n,f=window.uauth.validateAuthUrl(e,r);if(t==="navigate"){const n=document.createElement("form");n.method="POST";n.action=f;const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=u??"";n.appendChild(t);const e=document.createElement("input");if(e.type="hidden",e.name="__uauth_device",e.value=window.uauth.deviceId,n.appendChild(e),i)for(const t in i){const r=document.createElement("input");r.type="hidden";r.name=t;r.value=i[t];n.appendChild(r)}document.body.appendChild(n);try{await window.uauth.submitForm(n,r)}catch(o){n.remove();throw o;}return null}const s=t==="logout"||t==="logout-observe";return window.uauth.request({url:f,method:"POST",payload:i,applicationProfile:u,contentType:"form",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:r,accessToken:o,navigateOnSuccess:t==="logout",headers:s?{"X-UAuth-Logout-Mode":"observe"}:{}})};window.uauth.postJson=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"POST",payload:n.payload,applicationProfile:n.applicationProfile,contentType:"json",accessToken:n.accessToken??null,credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:n.trustedOrigin})};window.uauth.request=async function(n){const{followRedirects:d=!1,navigateOnSuccess:g=!1,url:l,method:nt="GET",payload:e=null,applicationProfile:a="",contentType:v="json",credentials:h="same-origin",accessToken:r=null,headers:tt={}}=n;if(!l)throw new Error("Request URL is required.");const i=new URL(l,document.baseURI);if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported request URL protocol.");const u=nt.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(u))throw new Error(`Unsupported HTTP method: ${u}`);if(!["same-origin","include","omit"].includes(h))throw new Error("Invalid credentials policy.");if(h==="include"&&i.origin!==window.location.origin&&!n.allowCrossOriginCredentials)throw new Error("Cross-origin credentials require explicit authorization.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const f={...tt,"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":a,"X-Requested-With":"UAuth"};if(r!==null){if(typeof r!="string"||r.length===0||/[\r\n]/.test(r))throw new Error("Invalid authentication access token.");if(i.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(i.hostname))throw new Error("Bearer access token requests require HTTPS.");const t=window.uauth.validateAuthUrl(i.href,n.trustedOrigin);if(new URL(t).origin!==i.origin)throw new Error("Invalid authentication token destination.");f.Authorization=`Bearer ${r}`}let o=null;if(e!==null&&e!==undefined){if(u==="GET")throw new Error("GET requests cannot contain a body.");if(v==="json")f["Content-Type"]="application/json",o=JSON.stringify(e);else if(v==="form"){f["Content-Type"]="application/x-www-form-urlencoded";o=new URLSearchParams;for(const[n,t]of Object.entries(e))o.append(n,t??"")}else throw new Error("Unsupported content type.");}if(u!=="GET"&&n.antiforgery===!0){const u=window.uauth.validateAuthUrl(window.uauth.antiforgery.tokenUrl,n.trustedOrigin);if(new URL(u).origin!==i.origin)throw new Error("UAuth antiforgery token origin differs from request origin.");const t=await window.uauth.antiforgery.getToken(n.trustedOrigin,r,a);f[t.headerName]=t.requestToken}let t;try{t=await fetch(i.href,{method:u,credentials:h,redirect:d?"follow":"error",headers:f,body:o})}catch(y){if(y instanceof TypeError)return{ok:!1,status:0,refreshOutcome:null,body:null};throw y;}let s=null;if(t.status!==204&&t.status!==205){const n=await t.text();if(n)try{s=JSON.parse(n)}catch{s=n}}if(g&&t.ok){const n=s?.redirectUrl;if(typeof n=="string"&&n.length>0){const t=new URL(n,window.location.origin);if(!["http:","https:"].includes(t.protocol))throw new Error("Invalid logout redirect protocol.");window.location.assign(t.href)}}const c=t.headers.get("X-UAuth-Access-Header");let p=null,w=null,b=null,k=null;if(t.ok&&c){if(!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(c))throw new Error("Invalid access token header name.");p=t.headers.get(c);w=t.headers.get("X-UAuth-Access-Expires");b=t.headers.get("X-UAuth-Access-Format");k=t.headers.get("X-UAuth-Access-HeaderFormat")}return{retryAfter:t.headers.get("Retry-After"),ok:t.ok,status:t.status,refreshOutcome:t.headers.get("X-UAuth-Refresh"),accessToken:p,accessTokenExpiresAt:w,accessTokenFormat:b,accessTokenHeaderFormat:k,body:s}};window.uauth.resourceRequest=async function(n){const{url:s,baseAddress:l,method:y="GET",payload:e=null,applicationProfile:p="",credentials:w="Auto",accessToken:u=null,requestId:f}=n;if(!s||typeof s!="string")throw new Error("Resource request URL is required.");const i=l?new URL(l):new URL(window.location.origin+"/");if(!["http:","https:"].includes(i.protocol))throw new Error("Invalid Resource API protocol.");if(i.username||i.password||i.search||i.hash)throw new Error("Invalid Resource API base address.");const t=new URL(s,i);if(t.origin!==i.origin)throw new Error("Resource request target differs from configured API origin.");if(t.username||t.password)throw new Error("Resource URL cannot contain credentials.");if(!["http:","https:"].includes(t.protocol))throw new Error("Unsupported Resource API protocol.");const h=y.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(h))throw new Error("Unsupported Resource API method.");if(h==="GET"&&e!==null)throw new Error("GET requests cannot contain a body.");let r;switch(w.toLowerCase()){case"auto":r=t.origin===window.location.origin?"same-origin":"include";break;case"sameorigin":r="same-origin";break;case"include":r="include";break;case"omit":r="omit";break;default:throw new Error("Invalid Resource credentials mode.");}if(r==="include"&&t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Cross-origin credential requests require HTTPS.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const c={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":p,"X-Requested-With":"UAuth"};if(u!==null){if(typeof u!="string"||u.length===0||/[\r\n]/.test(u))throw new Error("Invalid Resource API access token.");if(t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Bearer access token requests require HTTPS.");c.Authorization=`Bearer ${u}`}let a=null;e!==null&&e!==undefined&&(c["Content-Type"]="application/json",a=JSON.stringify(e));const v=new AbortController;if(f){if(window.uauth.resourceRequests.has(f))throw new Error("Duplicate Resource request ID.");window.uauth.resourceRequests.set(f,v)}try{const n=await fetch(t.href,{method:h,credentials:r,redirect:"error",headers:c,body:a,signal:v.signal});let i=null;if(n.status!==204&&n.status!==205){const t=await n.text();t.length>0&&(i=t)}return{retryAfter:n.headers.get("Retry-After"),ok:n.ok,status:n.status,body:i,contentType:n.headers.get("Content-Type")}}catch(o){if(o?.name==="AbortError")throw o;if(o instanceof TypeError)return{ok:!1,status:0,body:null,contentType:null};throw o;}finally{f&&window.uauth.resourceRequests.delete(f)}};window.uauth.resourceRequests=new Map;window.uauth.cancelResourceRequest=function(n){const t=window.uauth.resourceRequests.get(n);return t?(t.abort(),!0):!1};window.uauth.validateAuthUrl=function(n,t=null){if(!n||typeof n!="string")throw new Error("Authentication URL is required.");const r=t?new URL(t,window.location.origin):new URL(window.location.origin),i=new URL(n,document.baseURI);if(!["http:","https:"].includes(r.protocol))throw new Error("Unsupported trusted origin protocol.");if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported authentication URL protocol.");if(r.username||r.password)throw new Error("Trusted origin cannot contain credentials.");if(i.username||i.password)throw new Error("Authentication URL cannot contain credentials.");if(i.origin!==r.origin)throw new Error("Authentication request target differs from the trusted UAuthHub origin.");return i.href};window.uauth.commitLoginForm=async function(n,t,i,r){const f=new FormData(n),u=Object.create(null);for(const[n,t]of f.entries()){if(typeof t!="string")throw new Error("File values are not supported in login forms.");if(Object.hasOwn(u,n))throw new Error(`Duplicate login form field: ${n}.`);u[n]=t}if(Object.hasOwn(u,"__uauth_response_mode"))throw new Error("Reserved UAuth form field.");return u.__uauth_response_mode="fetch",window.uauth.post({url:t,mode:"fetch",data:u,applicationProfile:i,trustedOrigin:r})};window.uauth.getLoginTransport=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"GET",applicationProfile:n.applicationProfile,credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!1,trustedOrigin:n.trustedOrigin})};window.uauth.antiforgery={tokenUrl:null,configure:function(n){if(!n?.tokenUrl)throw new Error("UAuth antiforgery token URL is required.");this.tokenUrl=window.uauth.validateAuthUrl(n.tokenUrl,n.trustedOrigin)},getToken:async function(n,t=null,i=""){if(!this.tokenUrl)throw new Error("UAuth antiforgery is not configured.");const f=window.uauth.validateAuthUrl(this.tokenUrl,n),e={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":i};if(t!==null){if(typeof t!="string"||t.length===0||/[\r\n]/.test(t))throw new Error("Invalid UAuth access token.");const n=new URL(f);if(n.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(n.hostname))throw new Error("Bearer access token requests require HTTPS.");e.Authorization=`Bearer ${t}`}const u=await fetch(f,{method:"GET",credentials:"include",cache:"no-store",redirect:"error",headers:e});if(!u.ok)throw new Error(`Unable to obtain UAuth antiforgery token: HTTP ${u.status}.`);const r=await u.json();if(!r?.requestToken||!r?.headerName||!r?.formFieldName)throw new Error("Invalid UAuth antiforgery response.");return r},appendToForm:async function(n,t){const r=await this.getToken(t);let i=Array.from(n.elements).find(n=>n.name===r.formFieldName);i||(i=document.createElement("input"),i.type="hidden",i.name=r.formFieldName,n.appendChild(i));i.value=r.requestToken}};window.uauth.submitLoginForm=async function(n,t){if(!(n instanceof HTMLFormElement))throw new Error("A native HTML form is required.");const{mode:o,tryUrl:k,commitUrl:d,applicationProfile:s,trustedOrigin:f,isPkce:h,transport:c="Auto",transportUrl:g,returnUrl:nt}=t;if(!["TryOnly","TryAndCommit","DirectCommit"].includes(o))throw new Error("Unsupported UAuth submit mode.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const v=window.uauth.validateAuthUrl(d,f),tt=o==="DirectCommit"?null:window.uauth.validateAuthUrl(k,f),u=new FormData(n),y=u.getAll("Identifier"),p=u.getAll("Secret");if(y.length!==1||p.length!==1)throw new Error("Login form requires exactly one Identifier and one Secret.");const l=y[0],a=p[0];if(typeof l!="string"||typeof a!="string"||!l.trim()||!a.trim())throw new Error("Identifier and Secret are required.");if(h)for(const n of["authorization_code","code_verifier"]){const t=u.getAll(n);if(t.length!==1||typeof t[0]!="string"||!t[0])throw new Error(`Missing or duplicate PKCE field: ${n}`);}if(h){const t=u.get("hub_session_id");if(typeof t!="string"||!t)throw new Error("Missing PKCE Hub session ID.");const i=new URL(v);i.searchParams.set("uauth_hub",t);n.action=i.href}else n.action=v;const w=async()=>{if(!["Auto","Fetch","Navigation"].includes(c))throw new Error("Unsupported login transport.");const t=await window.uauth.getLoginTransport({url:g,applicationProfile:s,trustedOrigin:f});if(!t?.ok||!t.body?.supported)throw new Error("Login transport is unavailable or unsupported.");const i=t.body,u=c==="Auto"?i.navigationSupported&&Boolean(nt)?"Navigation":"Fetch":c;if(u==="Navigation"){if(!i.navigationSupported)throw new Error("Navigation is incompatible with header-based credential delivery.");return await window.uauth.submitForm(n,f),null}const r=await window.uauth.commitLoginForm(n,n.action,s,f);if(!r?.ok)throw new Error(`Login commit failed: HTTP ${r?.status??0}.`);return{commit:r,accessTokenInHeader:i.accessTokenInHeader}};if(o==="DirectCommit")return await w();const e={Identifier:l,Secret:a};h?(e.authorization_code=u.get("authorization_code"),e.code_verifier=u.get("code_verifier"),e.__uauth_return_url=u.get("__uauth_return_url")??"",e.hub_session_id=u.get("hub_session_id")??""):e.ReturnUrl=u.get("__uauth_return_url")??"";const i=await window.uauth.postJson({url:tt,payload:e,applicationProfile:s,trustedOrigin:f});if(!i||!Number.isInteger(i.status))throw new Error("Invalid UAuth transport response.");if(i.status===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:i.retryAfter??null};const it=i.status>=200&&i.status<300,b=i.status>=400&&i.status<500;if(!it&&!b)throw new Error(`Unexpected UAuth try response: HTTP ${i.status}.`);const r=i.body;if(!r||typeof r!="object"||Array.isArray(r)||typeof r.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(b&&r.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");if(o==="TryAndCommit"&&r.isSuccess){if(r.previewReceipt){let t=Array.from(n.elements).find(n=>n.name==="PreviewReceipt");t||(t=document.createElement("input"),t.type="hidden",t.name="PreviewReceipt",n.appendChild(t));t.value=r.previewReceipt}const t=await w();if(t)return{...r,...t}}return r};window.uauth.setDeviceId=function(n){window.uauth.deviceId=n};window.uauth.getDeviceInfo=function(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language}} \ No newline at end of file +window.uauth=window.uauth||{};window.uauth.storage={set:function(n,t,i){const r=n==="local"?window.localStorage:window.sessionStorage;r.setItem(t,i)},get:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)},remove:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;i.removeItem(t)},exists:function(n,t){const i=n==="local"?window.localStorage:window.sessionStorage;return i.getItem(t)!==null}};window.uauth.submitForm=async function(n,t=null){if(!n)return;if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const r=window.uauth.validateAuthUrl(n.action,t);n.action=r;let i=n.querySelector("input[name='__uauth_device']");i||(i=document.createElement("input"),i.type="hidden",i.name="__uauth_device",n.appendChild(i));i.value=window.uauth.deviceId;await window.uauth.antiforgery.appendToForm(n,t);n.submit()};window.uauth.tryAndCommit=async function(n){const{tryUrl:c,commitUrl:l,data:e,applicationProfile:o,trustedOrigin:u}=n,a=window.uauth.validateAuthUrl(c,u),v=window.uauth.validateAuthUrl(l,u),s=window.uauth.deviceId;if(!s)throw new Error("UAuth deviceId is not initialized.");const r=await window.uauth.postJson({url:a,payload:e,applicationProfile:o,trustedOrigin:u});if(!r||!Number.isInteger(r.status))throw new Error("Invalid UAuth transport response.");const i=r.status;if(i===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:r.retryAfter??null};const y=i>=200&&i<300,h=i>=400&&i<500;if(!y&&!h)throw new Error(`Unexpected UAuth try response: HTTP ${i}.`);const t=r.body;if(!t||typeof t!="object"||Array.isArray(t)||typeof t.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(h&&t.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");const f={isSuccess:t.isSuccess,reason:t.reason??null,remainingAttempts:t.remainingAttempts??null,lockoutUntilUtc:t.lockoutUntilUtc??null,requiresMfa:t.requiresMfa??!1,retryWithNewPkce:t.retryWithNewPkce??!1,previewReceipt:t.previewReceipt??null};if(f.isSuccess){const n=document.createElement("form");n.method="POST";n.action=v;for(const t of Object.keys(e)){const i=document.createElement("input");i.type="hidden";i.name=t;i.value=e[t]??"";n.appendChild(i)}if(f.previewReceipt){const t=document.createElement("input");t.type="hidden";t.name="PreviewReceipt";t.value=f.previewReceipt;n.appendChild(t)}const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=o??"";n.appendChild(t);const i=document.createElement("input");i.type="hidden";i.name="__uauth_device";i.value=s;n.appendChild(i);document.body.appendChild(n);try{await window.uauth.submitForm(n,u)}catch(r){n.remove();throw r;}}return f};window.uauth.post=async function(n){const{url:e,mode:t,data:i,applicationProfile:u,trustedOrigin:r,accessToken:o=null}=n,f=window.uauth.validateAuthUrl(e,r);if(t==="navigate"){const n=document.createElement("form");n.method="POST";n.action=f;const t=document.createElement("input");t.type="hidden";t.name="__uauth_application_profile";t.value=u??"";n.appendChild(t);const e=document.createElement("input");if(e.type="hidden",e.name="__uauth_device",e.value=window.uauth.deviceId,n.appendChild(e),i)for(const t in i){const r=document.createElement("input");r.type="hidden";r.name=t;r.value=i[t];n.appendChild(r)}document.body.appendChild(n);try{await window.uauth.submitForm(n,r)}catch(o){n.remove();throw o;}return null}const s=t==="logout"||t==="logout-observe";return window.uauth.request({url:f,method:"POST",payload:i,applicationProfile:u,contentType:"form",credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:r,accessToken:o,navigateOnSuccess:t==="logout",headers:s?{"X-UAuth-Logout-Mode":"observe"}:{}})};window.uauth.postJson=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"POST",payload:n.payload,applicationProfile:n.applicationProfile,contentType:"json",accessToken:n.accessToken??null,credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!0,trustedOrigin:n.trustedOrigin})};window.uauth.request=async function(n){const{followRedirects:d=!1,navigateOnSuccess:g=!1,url:l,method:nt="GET",payload:e=null,applicationProfile:a="",contentType:v="json",credentials:h="same-origin",accessToken:r=null,headers:tt={}}=n;if(!l)throw new Error("Request URL is required.");const i=new URL(l,document.baseURI);if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported request URL protocol.");const u=nt.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(u))throw new Error(`Unsupported HTTP method: ${u}`);if(!["same-origin","include","omit"].includes(h))throw new Error("Invalid credentials policy.");if(h==="include"&&i.origin!==window.location.origin&&!n.allowCrossOriginCredentials)throw new Error("Cross-origin credentials require explicit authorization.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const f={...tt,"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":a,"X-Requested-With":"UAuth"};if(r!==null){if(typeof r!="string"||r.length===0||/[\r\n]/.test(r))throw new Error("Invalid authentication access token.");if(i.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(i.hostname))throw new Error("Bearer access token requests require HTTPS.");const t=window.uauth.validateAuthUrl(i.href,n.trustedOrigin);if(new URL(t).origin!==i.origin)throw new Error("Invalid authentication token destination.");f.Authorization=`Bearer ${r}`}let o=null;if(e!==null&&e!==undefined){if(u==="GET")throw new Error("GET requests cannot contain a body.");if(v==="json")f["Content-Type"]="application/json",o=JSON.stringify(e);else if(v==="form"){f["Content-Type"]="application/x-www-form-urlencoded";o=new URLSearchParams;for(const[n,t]of Object.entries(e))o.append(n,t??"")}else throw new Error("Unsupported content type.");}if(u!=="GET"&&n.antiforgery===!0){const u=window.uauth.validateAuthUrl(window.uauth.antiforgery.tokenUrl,n.trustedOrigin);if(new URL(u).origin!==i.origin)throw new Error("UAuth antiforgery token origin differs from request origin.");const t=await window.uauth.antiforgery.getToken(n.trustedOrigin,r,a);f[t.headerName]=t.requestToken}let t;try{t=await fetch(i.href,{method:u,credentials:h,redirect:d?"follow":"error",headers:f,body:o})}catch(y){if(y instanceof TypeError)return{ok:!1,status:0,refreshOutcome:null,body:null};throw y;}let s=null;if(t.status!==204&&t.status!==205){const n=await t.text();if(n)try{s=JSON.parse(n)}catch{s=n}}if(g&&t.ok){const n=s?.redirectUrl;if(typeof n=="string"&&n.length>0){const t=new URL(n,window.location.origin);if(!["http:","https:"].includes(t.protocol))throw new Error("Invalid logout redirect protocol.");window.location.assign(t.href)}}const c=t.headers.get("X-UAuth-Access-Header");let p=null,w=null,b=null,k=null;if(t.ok&&c){if(!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(c))throw new Error("Invalid access token header name.");p=t.headers.get(c);w=t.headers.get("X-UAuth-Access-Expires");b=t.headers.get("X-UAuth-Access-Format");k=t.headers.get("X-UAuth-Access-HeaderFormat")}return{retryAfter:t.headers.get("Retry-After"),ok:t.ok,status:t.status,refreshOutcome:t.headers.get("X-UAuth-Refresh"),authRecovery:t.headers.get("X-UAuth-Auth-Recovery"),accessToken:p,accessTokenExpiresAt:w,accessTokenFormat:b,accessTokenHeaderFormat:k,body:s}};window.uauth.resourceRequest=async function(n){const{url:s,baseAddress:l,method:y="GET",payload:e=null,applicationProfile:p="",credentials:w="Auto",accessToken:u=null,requestId:f}=n;if(!s||typeof s!="string")throw new Error("Resource request URL is required.");const i=l?new URL(l):new URL(window.location.origin+"/");if(!["http:","https:"].includes(i.protocol))throw new Error("Invalid Resource API protocol.");if(i.username||i.password||i.search||i.hash)throw new Error("Invalid Resource API base address.");const t=new URL(s,i);if(t.origin!==i.origin)throw new Error("Resource request target differs from configured API origin.");if(t.username||t.password)throw new Error("Resource URL cannot contain credentials.");if(!["http:","https:"].includes(t.protocol))throw new Error("Unsupported Resource API protocol.");const h=y.toUpperCase();if(!["GET","POST","PUT","PATCH","DELETE"].includes(h))throw new Error("Unsupported Resource API method.");if(h==="GET"&&e!==null)throw new Error("GET requests cannot contain a body.");let r;switch(w.toLowerCase()){case"auto":r=t.origin===window.location.origin?"same-origin":"include";break;case"sameorigin":r="same-origin";break;case"include":r="include";break;case"omit":r="omit";break;default:throw new Error("Invalid Resource credentials mode.");}if(r==="include"&&t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Cross-origin credential requests require HTTPS.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const c={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":p,"X-Requested-With":"UAuth"};if(u!==null){if(typeof u!="string"||u.length===0||/[\r\n]/.test(u))throw new Error("Invalid Resource API access token.");if(t.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(t.hostname))throw new Error("Bearer access token requests require HTTPS.");c.Authorization=`Bearer ${u}`}let a=null;e!==null&&e!==undefined&&(c["Content-Type"]="application/json",a=JSON.stringify(e));const v=new AbortController;if(f){if(window.uauth.resourceRequests.has(f))throw new Error("Duplicate Resource request ID.");window.uauth.resourceRequests.set(f,v)}try{const n=await fetch(t.href,{method:h,credentials:r,redirect:"error",headers:c,body:a,signal:v.signal});let i=null;if(n.status!==204&&n.status!==205){const t=await n.text();t.length>0&&(i=t)}return{retryAfter:n.headers.get("Retry-After"),authRecovery:n.headers.get("X-UAuth-Auth-Recovery"),ok:n.ok,status:n.status,body:i,contentType:n.headers.get("Content-Type")}}catch(o){if(o?.name==="AbortError")throw o;if(o instanceof TypeError)return{ok:!1,status:0,body:null,contentType:null};throw o;}finally{f&&window.uauth.resourceRequests.delete(f)}};window.uauth.resourceRequests=new Map;window.uauth.cancelResourceRequest=function(n){const t=window.uauth.resourceRequests.get(n);return t?(t.abort(),!0):!1};window.uauth.validateAuthUrl=function(n,t=null){if(!n||typeof n!="string")throw new Error("Authentication URL is required.");const r=t?new URL(t,window.location.origin):new URL(window.location.origin),i=new URL(n,document.baseURI);if(!["http:","https:"].includes(r.protocol))throw new Error("Unsupported trusted origin protocol.");if(!["http:","https:"].includes(i.protocol))throw new Error("Unsupported authentication URL protocol.");if(r.username||r.password)throw new Error("Trusted origin cannot contain credentials.");if(i.username||i.password)throw new Error("Authentication URL cannot contain credentials.");if(i.origin!==r.origin)throw new Error("Authentication request target differs from the trusted UAuthHub origin.");return i.href};window.uauth.commitLoginForm=async function(n,t,i,r){const f=new FormData(n),u=Object.create(null);for(const[n,t]of f.entries()){if(typeof t!="string")throw new Error("File values are not supported in login forms.");if(Object.hasOwn(u,n))throw new Error(`Duplicate login form field: ${n}.`);u[n]=t}if(Object.hasOwn(u,"__uauth_response_mode"))throw new Error("Reserved UAuth form field.");return u.__uauth_response_mode="fetch",window.uauth.post({url:t,mode:"fetch",data:u,applicationProfile:i,trustedOrigin:r})};window.uauth.getLoginTransport=function(n){const t=window.uauth.validateAuthUrl(n.url,n.trustedOrigin);return window.uauth.request({url:t,method:"GET",applicationProfile:n.applicationProfile,credentials:"include",allowCrossOriginCredentials:!0,antiforgery:!1,trustedOrigin:n.trustedOrigin})};window.uauth.antiforgery={tokenUrl:null,configure:function(n){if(!n?.tokenUrl)throw new Error("UAuth antiforgery token URL is required.");this.tokenUrl=window.uauth.validateAuthUrl(n.tokenUrl,n.trustedOrigin)},getToken:async function(n,t=null,i=""){if(!this.tokenUrl)throw new Error("UAuth antiforgery is not configured.");const f=window.uauth.validateAuthUrl(this.tokenUrl,n),e={"X-UDID":window.uauth.deviceId,"X-UAuth-ApplicationProfile":i};if(t!==null){if(typeof t!="string"||t.length===0||/[\r\n]/.test(t))throw new Error("Invalid UAuth access token.");const n=new URL(f);if(n.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(n.hostname))throw new Error("Bearer access token requests require HTTPS.");e.Authorization=`Bearer ${t}`}const u=await fetch(f,{method:"GET",credentials:"include",cache:"no-store",redirect:"error",headers:e});if(!u.ok)throw new Error(`Unable to obtain UAuth antiforgery token: HTTP ${u.status}.`);const r=await u.json();if(!r?.requestToken||!r?.headerName||!r?.formFieldName)throw new Error("Invalid UAuth antiforgery response.");return r},appendToForm:async function(n,t){const r=await this.getToken(t);let i=Array.from(n.elements).find(n=>n.name===r.formFieldName);i||(i=document.createElement("input"),i.type="hidden",i.name=r.formFieldName,n.appendChild(i));i.value=r.requestToken}};window.uauth.submitLoginForm=async function(n,t){if(!(n instanceof HTMLFormElement))throw new Error("A native HTML form is required.");const{mode:o,tryUrl:k,commitUrl:d,applicationProfile:s,trustedOrigin:f,isPkce:h,transport:c="Auto",transportUrl:g,returnUrl:nt}=t;if(!["TryOnly","TryAndCommit","DirectCommit"].includes(o))throw new Error("Unsupported UAuth submit mode.");if(!window.uauth.deviceId)throw new Error("UAuth deviceId is not initialized.");const v=window.uauth.validateAuthUrl(d,f),tt=o==="DirectCommit"?null:window.uauth.validateAuthUrl(k,f),u=new FormData(n),y=u.getAll("Identifier"),p=u.getAll("Secret");if(y.length!==1||p.length!==1)throw new Error("Login form requires exactly one Identifier and one Secret.");const l=y[0],a=p[0];if(typeof l!="string"||typeof a!="string"||!l.trim()||!a.trim())throw new Error("Identifier and Secret are required.");if(h)for(const n of["authorization_code","code_verifier"]){const t=u.getAll(n);if(t.length!==1||typeof t[0]!="string"||!t[0])throw new Error(`Missing or duplicate PKCE field: ${n}`);}if(h){const t=u.get("hub_session_id");if(typeof t!="string"||!t)throw new Error("Missing PKCE Hub session ID.");const i=new URL(v);i.searchParams.set("uauth_hub",t);n.action=i.href}else n.action=v;const w=async()=>{if(!["Auto","Fetch","Navigation"].includes(c))throw new Error("Unsupported login transport.");const t=await window.uauth.getLoginTransport({url:g,applicationProfile:s,trustedOrigin:f});if(!t?.ok||!t.body?.supported)throw new Error("Login transport is unavailable or unsupported.");const i=t.body,u=c==="Auto"?i.navigationSupported&&Boolean(nt)?"Navigation":"Fetch":c;if(u==="Navigation"){if(!i.navigationSupported)throw new Error("Navigation is incompatible with header-based credential delivery.");return await window.uauth.submitForm(n,f),null}const r=await window.uauth.commitLoginForm(n,n.action,s,f);if(!r?.ok)throw new Error(`Login commit failed: HTTP ${r?.status??0}.`);return{commit:r,accessTokenInHeader:i.accessTokenInHeader}};if(o==="DirectCommit")return await w();const e={Identifier:l,Secret:a};h?(e.authorization_code=u.get("authorization_code"),e.code_verifier=u.get("code_verifier"),e.__uauth_return_url=u.get("__uauth_return_url")??"",e.hub_session_id=u.get("hub_session_id")??""):e.ReturnUrl=u.get("__uauth_return_url")??"";const i=await window.uauth.postJson({url:tt,payload:e,applicationProfile:s,trustedOrigin:f});if(!i||!Number.isInteger(i.status))throw new Error("Invalid UAuth transport response.");if(i.status===429)return{isSuccess:!1,status:429,errorCode:"rate_limited",retryAfter:i.retryAfter??null};const it=i.status>=200&&i.status<300,b=i.status>=400&&i.status<500;if(!it&&!b)throw new Error(`Unexpected UAuth try response: HTTP ${i.status}.`);const r=i.body;if(!r||typeof r!="object"||Array.isArray(r)||typeof r.isSuccess!="boolean")throw new Error("Invalid UAuth try response body.");if(b&&r.isSuccess)throw new Error("Successful authentication result returned with HTTP error.");if(o==="TryAndCommit"&&r.isSuccess){if(r.previewReceipt){let t=Array.from(n.elements).find(n=>n.name==="PreviewReceipt");t||(t=document.createElement("input"),t.type="hidden",t.name="PreviewReceipt",n.appendChild(t));t.value=r.previewReceipt}const t=await w();if(t)return{...r,...t}}return r};window.uauth.setDeviceId=function(n){window.uauth.deviceId=n};window.uauth.getDeviceInfo=function(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language}} \ No newline at end of file diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IClientStorage.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IClientStorage.cs index 2cbb2793..b556d78f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IClientStorage.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IClientStorage.cs @@ -1,6 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; - -namespace CodeBeam.UltimateAuth.Client.Infrastructure; +namespace CodeBeam.UltimateAuth.Client.Abstractions; /// /// Represents a storage mechanism for client-side data, allowing for setting, retrieving, removing, and checking the existence of key-value pairs within specified storage scopes. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshCoordinator.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshCoordinator.cs new file mode 100644 index 00000000..1f182994 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshCoordinator.cs @@ -0,0 +1,7 @@ +namespace CodeBeam.UltimateAuth.Client.Abstractions; + +public interface IUAuthRefreshCoordinator +{ + Task RefreshAsync(UAuthRefreshTrigger trigger, CancellationToken ct = default); + Task RefreshIfCurrentAsync(UAuthRefreshTrigger trigger, UAuthTokenSnapshot expected, CancellationToken ct = default); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshExecutor.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshExecutor.cs new file mode 100644 index 00000000..8dbcbb9a --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshExecutor.cs @@ -0,0 +1,6 @@ +namespace CodeBeam.UltimateAuth.Client.Abstractions; + +public interface IUAuthRefreshExecutor +{ + Task ExecuteAsync(UAuthRefreshTrigger trigger, UAuthTokenSnapshot expected); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshTransport.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshTransport.cs new file mode 100644 index 00000000..8decf7c9 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRefreshTransport.cs @@ -0,0 +1,10 @@ +namespace CodeBeam.UltimateAuth.Client.Abstractions; + +/// +/// Sends a refresh request through the raw client transport. +/// This operation must never trigger automatic authentication recovery. +/// +public interface IUAuthRefreshTransport +{ + Task SendAsync(CancellationToken ct = default); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestClient.cs similarity index 91% rename from src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthRequestClient.cs rename to src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestClient.cs index 257c9892..fe9b2f2e 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthRequestClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestClient.cs @@ -1,7 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Core.Contracts; - -namespace CodeBeam.UltimateAuth.Client.Infrastructure; +namespace CodeBeam.UltimateAuth.Client.Abstractions; /// /// Defines a client for sending requests to the UltimateAuth server, handling navigation, form submissions, JSON payloads, and transactional operations. @@ -44,6 +41,9 @@ Task SendFormAsync(string endpoint, IDictionary SendJsonAsync(string endpoint, object? payload = null, CancellationToken ct = default); + Task SendJsonAsync(string endpoint, object? payload, UAuthRequestAuthentication authentication, CancellationToken ct = default) + => SendJsonAsync(endpoint, payload, ct); + /// /// Attempts to perform a transactional operation by first trying the specified endpoint and, if successful, committing the operation to another endpoint. Returns the result of the try operation. /// diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestRecovery.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestRecovery.cs new file mode 100644 index 00000000..60445183 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthRequestRecovery.cs @@ -0,0 +1,8 @@ +namespace CodeBeam.UltimateAuth.Client.Abstractions; + +public interface IUAuthRequestRecovery +{ + Task PrepareAsync(CancellationToken ct = default); + + Task RecoverAsync(UAuthTokenSnapshot rejected, CancellationToken ct = default); +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthResourceRequestClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthResourceRequestClient.cs similarity index 64% rename from src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthResourceRequestClient.cs rename to src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthResourceRequestClient.cs index cc072aa0..b55c5f4f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/IUAuthResourceRequestClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthResourceRequestClient.cs @@ -1,6 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; - -namespace CodeBeam.UltimateAuth.Client.Infrastructure; +namespace CodeBeam.UltimateAuth.Client.Abstractions; public interface IUAuthResourceRequestClient { diff --git a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs index e8ca48b2..aa27acbf 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Abstractions/IUAuthTokenStore.cs @@ -16,6 +16,8 @@ public interface IUAuthTokenStore /// AccessToken? Read(); + UAuthTokenSnapshot Capture(); + /// /// Atomically replaces the current access token. /// @@ -25,4 +27,8 @@ public interface IUAuthTokenStore /// Removes the current access token. /// void Clear(); + + bool TryRotate(UAuthTokenSnapshot expected, AccessToken token); + + bool TryClear(UAuthTokenSnapshot expected); } diff --git a/src/client/CodeBeam.UltimateAuth.Client/AuthState/UAuthStateManager.cs b/src/client/CodeBeam.UltimateAuth.Client/AuthState/UAuthStateManager.cs index b7fba47c..2a6a097f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/AuthState/UAuthStateManager.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/AuthState/UAuthStateManager.cs @@ -18,12 +18,16 @@ internal sealed class UAuthStateManager : IUAuthStateManager, IDisposable private readonly IClock _clock; private readonly IUAuthTokenStore _tokenStore; private readonly IUAuthRequestClient _requestClient; + private readonly UAuthRefreshSchedule _refreshSchedule; + private readonly IUAuthRefreshCoordinator _refreshCoordinator; private readonly UAuthClientOptions _options; private Task? _ensureTask; private DateTimeOffset _validationNotBefore; private readonly object _ensureLock = new(); private bool _initialRecoveryCompleted; + private long? _ensureEpoch; + private long? _validationThrottleEpoch; public UAuthState State { get; } = UAuthState.Anonymous(); @@ -33,6 +37,8 @@ public UAuthStateManager( IClock clock, IUAuthTokenStore tokenStore, IUAuthRequestClient requestClient, + UAuthRefreshSchedule refreshSchedule, + IUAuthRefreshCoordinator refreshCoordinator, IOptions options) { _client = client; @@ -40,6 +46,8 @@ public UAuthStateManager( _clock = clock; _tokenStore = tokenStore; _requestClient = requestClient; + _refreshSchedule = refreshSchedule; + _refreshCoordinator = refreshCoordinator; _options = options.Value; _events.StateChanged += HandleStateEvent; @@ -48,72 +56,137 @@ public UAuthStateManager( public Task EnsureAsync(bool force = false, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - if (_clock.UtcNow < _validationNotBefore) return Task.CompletedTask; - if (!force && State.IsAuthenticated && !State.IsStale) - return Task.CompletedTask; + + Task task; + TaskCompletionSource? start = null; + UAuthTokenSnapshot? expected = null; lock (_ensureLock) { - if (_ensureTask is { IsCompleted: false }) - return _ensureTask; + var snapshot = _tokenStore.Capture(); + + if (_validationThrottleEpoch == snapshot.Epoch && _clock.UtcNow < _validationNotBefore) + { + return Task.CompletedTask; + } + + if (_ensureTask is { IsCompleted: false } && _ensureEpoch == snapshot.Epoch) + { + return _ensureTask.WaitAsync(ct); + } + + if (!force && State.IsAuthenticated && !State.IsStale && _refreshSchedule.IsAuthenticated(snapshot)) + { + return Task.CompletedTask; + } + + start = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _ensureTask = EnsureInternalAsync(ct); - return _ensureTask; + expected = snapshot; + _ensureTask = start.Task; + _ensureEpoch = snapshot.Epoch; + task = start.Task; } + + _ = EnsureInternalAsync(expected!, start!); + + return task.WaitAsync(ct); } - private async Task EnsureInternalAsync(CancellationToken ct) + private async Task EnsureInternalAsync(UAuthTokenSnapshot expected, TaskCompletionSource completion) { try { + if (!IsCurrentEpoch(expected)) + return; + var result = await _client.Flows.ValidateAsync(); + if (!IsCurrentEpoch(expected)) + return; + if (!_initialRecoveryCompleted) { if (result.State == SessionState.NotFound) { - var recovered = - await TryRecoverAuthenticationAsync(ct); + var recovered = await TryRecoverAuthenticationAsync(expected, CancellationToken.None); + + if (!IsCurrentEpoch(expected)) + return; if (recovered) { result = await _client.Flows.ValidateAsync(); + + if (!IsCurrentEpoch(expected)) + return; } } _initialRecoveryCompleted = true; } - if (!result.IsValid) + lock (_ensureLock) { - State.Clear(); - return; - } + if (!IsCurrentEpoch(expected)) + return; - if (result.Snapshot is null) - { - State.MarkStale(); - return; - } + if (!result.IsValid) + { + ClearAuthenticationState(expected); + return; + } + + if (result.Snapshot is null) + { + State.MarkStale(); + return; + } + + _refreshSchedule.MarkAuthenticated(expected); - State.ApplySnapshot(result.Snapshot, _clock.UtcNow); + State.ApplySnapshot(result.Snapshot, _clock.UtcNow); + } } catch (UAuthTransportException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests) { - _validationNotBefore = UAuthRateLimit.NotBefore( - _clock.UtcNow, - ex.RetryAfter); + lock (_ensureLock) + { + if (IsCurrentEpoch(expected)) + { + _validationThrottleEpoch = expected.Epoch; + + _validationNotBefore = UAuthRateLimit.NotBefore( + _clock.UtcNow, + ex.RetryAfter); + } + } + } + catch (Exception ex) + { + completion.TrySetException(ex); } finally { lock (_ensureLock) { - _ensureTask = null; + if (ReferenceEquals(_ensureTask, completion.Task)) + { + _ensureTask = null; + _ensureEpoch = null; + } } + + completion.TrySetResult(); } } + private bool IsCurrentEpoch(UAuthTokenSnapshot expected) + { + return _tokenStore.Capture().Epoch == expected.Epoch; + } + private async Task HandleStateEvent(UAuthStateEventArgs args) { switch (args.Type) @@ -123,8 +196,21 @@ private async Task HandleStateEvent(UAuthStateEventArgs args) return; case UAuthStateEvent.ReauthenticationRequired: - State.Clear(); - return; + { + if (args is UAuthStateEventArgs reauth) + { + if (_tokenStore.Capture().Epoch != reauth.Payload) + return; + + // Executor already cleared the token store. + _refreshSchedule.MarkUnauthenticated(); + State.Clear(); + return; + } + + ClearAuthenticationState(); + return; + } } if (args.RefreshMode == UAuthStateEventHandlingMode.None) @@ -136,7 +222,7 @@ private async Task HandleStateEvent(UAuthStateEventArgs args) case UAuthStateEvent.CredentialsChanged: case UAuthStateEvent.UserDeleted: case UAuthStateEvent.LogoutVariant: - State.Clear(); + ClearAuthenticationState(); return; } @@ -160,6 +246,9 @@ private async Task HandleStateEvent(UAuthStateEventArgs args) case UAuthStateEventHandlingMode.Patch: if (args.Type == UAuthStateEvent.ValidationCalled) { + if (_ensureTask is { IsCompleted: false }) + return; + State.MarkValidated(_clock.UtcNow); return; } @@ -177,7 +266,7 @@ public Task OnLoginAsync() public Task OnLogoutAsync() { - State.Clear(); + ClearAuthenticationState(); return Task.CompletedTask; } @@ -188,7 +277,7 @@ public void MarkStale() public void Clear() { - State.Clear(); + ClearAuthenticationState(); } public void Dispose() @@ -198,8 +287,13 @@ public void Dispose() public bool NeedsValidation => !State.IsAuthenticated || State.IsStale; - private async Task TryRecoverAuthenticationAsync(CancellationToken ct) + private async Task TryRecoverAuthenticationAsync(UAuthTokenSnapshot expected, CancellationToken ct) { + ct.ThrowIfCancellationRequested(); + + if (!IsCurrentEpoch(expected)) + return false; + var existingToken = _tokenStore.Read(); if (existingToken is not null && !existingToken.IsExpired(_clock.UtcNow)) @@ -211,12 +305,18 @@ private async Task TryRecoverAuthenticationAsync(CancellationToken ct) var transport = await _requestClient.GetLoginTransportAsync(transportUrl, ct); + if (!IsCurrentEpoch(expected)) + return false; + if (!transport.Supported || !transport.AccessTokenInHeader) { return false; } - var refresh = await _client.Flows.RecoverAsync(); + var refresh = await _refreshCoordinator.RefreshIfCurrentAsync(UAuthRefreshTrigger.Recovery, expected, ct); + + if (!IsCurrentEpoch(expected)) + return false; if (refresh.Status == 429) { @@ -226,7 +326,7 @@ refresh.RetryAfter is { } retryAfter : null); } - if (!refresh.IsSuccess) + if (!refresh.IsSuccess && refresh.ErrorCode != "token_changed") { return false; } @@ -235,4 +335,29 @@ refresh.RetryAfter is { } retryAfter return recoveredToken is not null && !recoveredToken.IsExpired(_clock.UtcNow); } + + private void ClearAuthenticationState() + { + ClearAuthenticationState(_tokenStore.Capture()); + } + + private void ClearAuthenticationState(UAuthTokenSnapshot expected) + { + bool cleared; + + lock (_ensureLock) + { + cleared = _tokenStore.TryClear(expected); + + if (cleared) + { + _refreshSchedule.MarkUnauthenticated(expected.Epoch); + } + } + + if (cleared) + { + State.Clear(); + } + } } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/CoordinatorTerminationReason.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/CoordinatorTerminationReason.cs index d3b69728..a9d82c51 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/CoordinatorTerminationReason.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/CoordinatorTerminationReason.cs @@ -1,4 +1,4 @@ -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Specifies why an UltimateAuth session coordinator stopped its active coordination cycle. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/RefreshResult.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/RefreshResult.cs index dfca87be..dd508feb 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/RefreshResult.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/RefreshResult.cs @@ -1,6 +1,6 @@ using CodeBeam.UltimateAuth.Core.Domain; -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Represents the result of an UltimateAuth session or token refresh operation. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/StorageScope.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/StorageScope.cs index 3a7120cb..1df3ebf4 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/StorageScope.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/StorageScope.cs @@ -1,4 +1,4 @@ -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Specifies the browser storage scope used for UltimateAuth client data. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/TenantTransport.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/TenantTransport.cs index d470db9d..0779bb8d 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/TenantTransport.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/TenantTransport.cs @@ -1,4 +1,4 @@ -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Specifies how tenant context is transported with UltimateAuth client requests. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRefreshTrigger.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRefreshTrigger.cs new file mode 100644 index 00000000..d7dc425a --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRefreshTrigger.cs @@ -0,0 +1,10 @@ +namespace CodeBeam.UltimateAuth.Client; + +public enum UAuthRefreshTrigger +{ + Reactive = 0, + Proactive = 10, + Background = 20, + Recovery = 30, + Manual = 40 +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRenderMode.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRenderMode.cs index ae3dd867..a79cca67 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRenderMode.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRenderMode.cs @@ -6,8 +6,7 @@ public enum UAuthRenderMode { /// - /// Does not automatically request a UI re-render in response to authentication - /// state change notifications. + /// Does not automatically request a UI re-render in response to authentication state change notifications. /// Manual = 0, diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestAuthentication.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestAuthentication.cs new file mode 100644 index 00000000..53595619 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestAuthentication.cs @@ -0,0 +1,17 @@ +namespace CodeBeam.UltimateAuth.Client; + +/// +/// Determines whether automatic authentication recovery is permitted for a request. +/// +public enum UAuthRequestAuthentication +{ + /// + /// Automatic authentication recovery is not permitted. + /// + None = 0, + + /// + /// Authentication recovery is permitted and the original request is automatically replayed. + /// + Recoverable = 10, +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestPreparationResult.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestPreparationResult.cs new file mode 100644 index 00000000..c7cb61bf --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthRequestPreparationResult.cs @@ -0,0 +1,6 @@ +namespace CodeBeam.UltimateAuth.Client; + +public sealed record UAuthRequestPreparationResult(UAuthTokenSnapshot Snapshot, RefreshResult? Failure = null) +{ + public bool CanProceed => Failure is null; +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthResourceTransportResult.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthResourceTransportResult.cs index b6fbfb99..b3b04087 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthResourceTransportResult.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthResourceTransportResult.cs @@ -1,6 +1,6 @@ using System.Text.Json.Serialization; -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Represents an HTTP response from an application resource. @@ -10,7 +10,6 @@ public sealed class UAuthResourceTransportResult [JsonPropertyName("ok")] public bool Ok { get; init; } - /// Raw Retry-After header, when exposed by the server/CORS policy. [JsonPropertyName("retryAfter")] public string? RetryAfter { get; init; } @@ -22,4 +21,13 @@ public sealed class UAuthResourceTransportResult [JsonPropertyName("contentType")] public string? ContentType { get; init; } + + /// + /// Indicates whether the server rejected the request before endpoint execution. + /// + [JsonPropertyName("authRecovery")] + public string? AuthRecovery { get; init; } + + [JsonIgnore] + public bool CanRecoverAuthentication => Status == 401 && string.Equals(AuthRecovery, "challenge", StringComparison.Ordinal); } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTokenSnapshot.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTokenSnapshot.cs new file mode 100644 index 00000000..b10c0f8d --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTokenSnapshot.cs @@ -0,0 +1,8 @@ +using CodeBeam.UltimateAuth.Core.Contracts; + +namespace CodeBeam.UltimateAuth.Client; + +public sealed record UAuthTokenSnapshot( + AccessToken? Token, + long Generation, + long Epoch); diff --git a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs index f00034de..c07ab50a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Contracts/UAuthTransportResult.cs @@ -1,7 +1,7 @@ using System.Text.Json; using System.Text.Json.Serialization; -namespace CodeBeam.UltimateAuth.Client.Contracts; +namespace CodeBeam.UltimateAuth.Client; /// /// Represents the transport-level result of an UltimateAuth client request. @@ -52,9 +52,19 @@ public sealed class UAuthTransportResult [JsonPropertyName("accessTokenHeaderFormat")] public string? AccessTokenHeaderFormat { get; init; } + /// + /// Indicates whether the server rejected the request before endpoint execution. + /// + [JsonPropertyName("authRecovery")] + public string? AuthRecovery { get; init; } + /// /// Gets the response body as JSON, when a body is available. /// [JsonPropertyName("body")] public JsonElement? Body { get; init; } + + + [JsonIgnore] + public bool CanRecoverAuthentication => Status == 401 && string.Equals(AuthRecovery, "challenge", StringComparison.Ordinal); } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdGenerator.cs b/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdGenerator.cs index bf73fae4..5a864d6f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdGenerator.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdGenerator.cs @@ -1,6 +1,6 @@ using CodeBeam.UltimateAuth.Core.Domain; -namespace CodeBeam.UltimateAuth.Client.Device; +namespace CodeBeam.UltimateAuth.Client; /// /// Represents a generator for device identifiers. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdStorage.cs b/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdStorage.cs index e6bbd169..e16a32f5 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdStorage.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Device/IDeviceIdStorage.cs @@ -1,4 +1,4 @@ -namespace CodeBeam.UltimateAuth.Client.Device; +namespace CodeBeam.UltimateAuth.Client; /// /// Represents a storage mechanism for device identifiers. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdGenerator.cs b/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdGenerator.cs index 8c1001b1..ced68691 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdGenerator.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdGenerator.cs @@ -1,8 +1,7 @@ -using CodeBeam.UltimateAuth.Client.Device; -using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Domain; using System.Security.Cryptography; -namespace CodeBeam.UltimateAuth.Client.Devices; +namespace CodeBeam.UltimateAuth.Client; internal sealed class UAuthDeviceIdGenerator : IDeviceIdGenerator { diff --git a/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdProvider.cs b/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdProvider.cs index 22cb4d31..adcc8d05 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdProvider.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Device/UAuthDeviceIdProvider.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Device; -using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Domain; namespace CodeBeam.UltimateAuth.Client; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Diagnostics/UAuthClientDiagnostics.cs b/src/client/CodeBeam.UltimateAuth.Client/Diagnostics/UAuthClientDiagnostics.cs index 21f4186e..d3b71a2a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Diagnostics/UAuthClientDiagnostics.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Diagnostics/UAuthClientDiagnostics.cs @@ -1,4 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client.Infrastructure; namespace CodeBeam.UltimateAuth.Client.Diagnostics; @@ -10,6 +10,24 @@ public sealed class UAuthClientDiagnostics private int _terminatedCount; private long _nextAutomaticRefreshTicks; + private readonly UAuthRefreshSchedule? _refreshSchedule; + + public UAuthClientDiagnostics() + { + } + + internal UAuthClientDiagnostics(UAuthRefreshSchedule refreshSchedule) + { + _refreshSchedule = refreshSchedule; + } + + /// + /// Gets the time at which the current authentication becomes eligible for a scheduled refresh. + ///

+ /// This does not represent a scheduled background request and does not include temporary refresh backoff. + ///
+ public DateTimeOffset? NextRefreshEligibleAt => _refreshSchedule?.GetNextRefreshEligibleAt(); + /// /// Occurs when any diagnostic information changes, allowing subscribers to react to updates in the client's state. /// @@ -70,20 +88,52 @@ public sealed class UAuthClientDiagnostics public int StopCount { get; private set; } + private int _manualRefreshCount; + private int _backgroundRefreshCount; + private int _proactiveRefreshCount; + private int _reactiveRefreshCount; + private int _recoveryRefreshCount; + + /// + /// Gets the number of manually initiated refresh transport attempts. + /// + public int ManualRefreshCount => Volatile.Read(ref _manualRefreshCount); + + /// + /// Gets the number of background refresh transport attempts. + /// + public int BackgroundRefreshCount => Volatile.Read(ref _backgroundRefreshCount); + + /// + /// Gets the number of proactive refresh transport attempts. + /// + public int ProactiveRefreshCount => Volatile.Read(ref _proactiveRefreshCount); + /// - /// Gets the total number of refresh attempts made by the client, which is incremented each time either the MarkManualRefresh or MarkAutomaticRefresh methods are called. + /// Gets the number of reactive refresh transport attempts. /// - public int RefreshAttemptCount { get; private set; } + public int ReactiveRefreshCount => Volatile.Read(ref _reactiveRefreshCount); /// - /// Gets the total number of manual refresh attempts made by the client, which is incremented each time the MarkManualRefresh method is called. + /// Gets the number of initial authentication recovery refresh transport attempts. /// - public int ManualRefreshCount { get; private set; } + public int RecoveryRefreshCount => Volatile.Read(ref _recoveryRefreshCount); /// - /// Gets the total number of automatic refresh attempts made by the client, which is incremented each time the MarkAutomaticRefresh method is called. + /// Gets the combined number of background, proactive and reactive refresh transport attempts. /// - public int AutomaticRefreshCount { get; private set; } + public int AutomaticRefreshCount => + BackgroundRefreshCount + + ProactiveRefreshCount + + ReactiveRefreshCount; + + /// + /// Gets the total number of refresh transport attempts. + /// + public int RefreshAttemptCount => + ManualRefreshCount + + AutomaticRefreshCount + + RecoveryRefreshCount; /// @@ -153,19 +203,37 @@ internal void MarkStopped() Changed?.Invoke(); } - internal void MarkManualRefresh() + internal void MarkRefreshAttempt(UAuthRefreshTrigger trigger) { - RefreshAttemptCount++; - ManualRefreshCount++; - Changed?.Invoke(); - } + switch (trigger) + { + case UAuthRefreshTrigger.Manual: + Interlocked.Increment(ref _manualRefreshCount); + break; + + case UAuthRefreshTrigger.Background: + Interlocked.Increment(ref _backgroundRefreshCount); + break; + + case UAuthRefreshTrigger.Proactive: + Interlocked.Increment(ref _proactiveRefreshCount); + break; + + case UAuthRefreshTrigger.Reactive: + Interlocked.Increment(ref _reactiveRefreshCount); + break; + + case UAuthRefreshTrigger.Recovery: + Interlocked.Increment(ref _recoveryRefreshCount); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(trigger)); + } - internal void MarkAutomaticRefresh() - { - RefreshAttemptCount++; - AutomaticRefreshCount++; Changed?.Invoke(); } + internal void MarkRefreshTouched() { RefreshTouchedCount++; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs b/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs index 503c0c0d..5a1b8e7f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Extensions/ServiceCollectionExtensions.cs @@ -1,7 +1,6 @@ using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Authentication; -using CodeBeam.UltimateAuth.Client.Device; -using CodeBeam.UltimateAuth.Client.Devices; +using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -98,6 +97,8 @@ private static IServiceCollection AddUltimateAuthClientInternal(this IServiceCol services.AddSingleton, UAuthClientOptionsPostConfigure>(); services.TryAddSingleton(); services.AddScoped(); + services.TryAddScoped(); + services.TryAddScoped(sp => new UAuthClientDiagnostics(sp.GetRequiredService())); services.PostConfigure(o => { @@ -117,6 +118,11 @@ private static IServiceCollection AddUltimateAuthClientInternal(this IServiceCol services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.AddScoped(); services.TryAddScoped(); diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs index 2c168c02..03ab29d6 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/InMemoryUAuthTokenStore.cs @@ -1,29 +1,81 @@ -using System.Threading; -using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Core.Contracts; namespace CodeBeam.UltimateAuth.Client.Infrastructure; -/// -/// Stores a single access token in managed memory. -/// -/// -/// The instance must be scoped to the current client or user. -/// It does not persist credentials across application restarts. -/// internal sealed class InMemoryUAuthTokenStore : IUAuthTokenStore { - private AccessToken? _token; + private readonly object _sync = new(); - public AccessToken? Read() - => Volatile.Read(ref _token); + private UAuthTokenSnapshot _snapshot = new(null, 0, 0); + + public AccessToken? Read() => Capture().Token; + + public UAuthTokenSnapshot Capture() => Volatile.Read(ref _snapshot); public void Replace(AccessToken token) { ArgumentNullException.ThrowIfNull(token); - Volatile.Write(ref _token, token); + + lock (_sync) + { + var current = _snapshot; + + Volatile.Write( + ref _snapshot, + new UAuthTokenSnapshot(token, current.Generation + 1, current.Epoch + 1)); + } } public void Clear() - => Volatile.Write(ref _token, null); + { + lock (_sync) + { + var current = _snapshot; + + Volatile.Write( + ref _snapshot, + new UAuthTokenSnapshot(null, current.Generation + 1, current.Epoch + 1)); + } + } + + public bool TryRotate(UAuthTokenSnapshot expected, AccessToken token) + { + ArgumentNullException.ThrowIfNull(token); + + lock (_sync) + { + var current = _snapshot; + + if (current.Epoch != expected.Epoch || current.Generation != expected.Generation) + { + return false; + } + + Volatile.Write( + ref _snapshot, + new UAuthTokenSnapshot(token, current.Generation + 1, current.Epoch)); + + return true; + } + } + + public bool TryClear(UAuthTokenSnapshot expected) + { + lock (_sync) + { + var current = _snapshot; + + if (current.Epoch != expected.Epoch || current.Generation != expected.Generation) + { + return false; + } + + Volatile.Write( + ref _snapshot, + new UAuthTokenSnapshot(null, current.Generation + 1, current.Epoch + 1)); + + return true; + } + } } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthLoginCompletion.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthLoginCompletion.cs index 414422b0..e980beb5 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthLoginCompletion.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthLoginCompletion.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Core.Contracts; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthPasswordClientValidator.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthPasswordClientValidator.cs index 13d8a380..6fc8fd8c 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthPasswordClientValidator.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthPasswordClientValidator.cs @@ -1,6 +1,7 @@ using CodeBeam.UltimateAuth.Credentials.Contracts; namespace CodeBeam.UltimateAuth.Client; + public static class UAuthPasswordClientValidator { public static IReadOnlyList Validate(string? password, UAuthPasswordPolicyInfo policy) diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRateLimit.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRateLimit.cs index 32923b4e..bd77272d 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRateLimit.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRateLimit.cs @@ -1,6 +1,5 @@ using System.Globalization; using System.Net; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Core.Contracts; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshCoordinator.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshCoordinator.cs new file mode 100644 index 00000000..21c21a62 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshCoordinator.cs @@ -0,0 +1,187 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Core.Domain; + +namespace CodeBeam.UltimateAuth.Client.Infrastructure; + +internal sealed class UAuthRefreshCoordinator : IUAuthRefreshCoordinator +{ + private readonly IUAuthRefreshExecutor _executor; + private readonly IUAuthTokenStore _tokenStore; + private readonly UAuthRefreshSchedule _refreshSchedule; + + private readonly object _sync = new(); + + private RefreshFlight? _inFlight; + + private sealed record RefreshFlight( + UAuthTokenSnapshot Expected, + UAuthRefreshTrigger Trigger, + TaskCompletionSource Completion) + { + public Task Task => Completion.Task; + } + + public UAuthRefreshCoordinator( + IUAuthRefreshExecutor executor, + IUAuthTokenStore tokenStore, + UAuthRefreshSchedule refreshSchedule) + { + _executor = executor; + _tokenStore = tokenStore; + _refreshSchedule = refreshSchedule; + } + + public Task RefreshAsync( + UAuthRefreshTrigger trigger, + CancellationToken ct = default) + { + return RunAsync( + trigger, + _tokenStore.Capture(), + ct); + } + + public Task RefreshIfCurrentAsync( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot expected, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(expected); + + return RunAsync(trigger, expected, ct); + } + + private async Task RunAsync( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot expected, + CancellationToken ct) + { + while (true) + { + ct.ThrowIfCancellationRequested(); + + RefreshFlight flight; + + bool startExecution = false; + bool waitAndReevaluate = false; + + lock (_sync) + { + var current = _tokenStore.Capture(); + + if (current.Epoch != expected.Epoch) + { + return Skipped("authentication_changed"); + } + + if (current.Generation != expected.Generation) + { + return Skipped("token_changed"); + } + + if (_inFlight is { Task.IsCompleted: false } active) + { + flight = active; + + waitAndReevaluate = + active.Expected.Epoch != expected.Epoch || + active.Expected.Generation != expected.Generation; + } + else + { + if (trigger is UAuthRefreshTrigger.Proactive + or UAuthRefreshTrigger.Background) + { + if (!_refreshSchedule.IsDue(current)) + { + return Skipped("refresh_not_due"); + } + } + + flight = new RefreshFlight( + current, + trigger, + new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously)); + + _inFlight = flight; + + startExecution = true; + } + } + + if (startExecution) + { + _ = ExecuteFlightAsync(flight); + } + + if (waitAndReevaluate) + { + try + { + await flight.Task.WaitAsync(ct); + } + catch (Exception) when (!ct.IsCancellationRequested) + { + // The completed flight belongs to another + // authentication lifecycle or generation. + } + + continue; + } + + var result = await flight.Task.WaitAsync(ct); + + ct.ThrowIfCancellationRequested(); + + // Initial recovery preserves authentication state on 401. + // Other triggers require their own failure semantics. + if (flight.Trigger == UAuthRefreshTrigger.Recovery && + trigger != UAuthRefreshTrigger.Recovery && + result.Status == 401 && + result.Outcome == RefreshOutcome.ReauthRequired) + { + continue; + } + + return result; + } + } + + private async Task ExecuteFlightAsync( + RefreshFlight flight) + { + try + { + var result = await _executor.ExecuteAsync( + flight.Trigger, + flight.Expected); + + flight.Completion.TrySetResult(result); + } + catch (Exception ex) + { + flight.Completion.TrySetException(ex); + } + finally + { + lock (_sync) + { + if (ReferenceEquals(_inFlight, flight)) + { + _inFlight = null; + } + } + } + } + + private static RefreshResult Skipped(string errorCode) + { + return new RefreshResult + { + IsSuccess = false, + Outcome = RefreshOutcome.None, + ErrorCode = errorCode + }; + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshExecutor.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshExecutor.cs new file mode 100644 index 00000000..76de8b86 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshExecutor.cs @@ -0,0 +1,405 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Diagnostics; +using CodeBeam.UltimateAuth.Client.Errors; +using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using System.Net; + +namespace CodeBeam.UltimateAuth.Client.Infrastructure; + +internal sealed class UAuthRefreshExecutor : IUAuthRefreshExecutor +{ + private readonly IUAuthRefreshTransport _transport; + private readonly IUAuthClientEvents _events; + private readonly IUAuthTokenStore _tokenStore; + private readonly UAuthRefreshSchedule _refreshSchedule; + private readonly UAuthClientDiagnostics _diagnostics; + private readonly IClock _clock; + + private DateTimeOffset _refreshNotBefore; + private RefreshResult? _refreshThrottle; + private long? _refreshThrottleEpoch; + private long? _noRotationEpoch; + private string? _noRotationToken; + private DateTimeOffset _noRotationNotBefore; + private RefreshResult? _noRotationResult; + + public UAuthRefreshExecutor( + IUAuthRefreshTransport transport, + IUAuthClientEvents events, + IUAuthTokenStore tokenStore, + UAuthRefreshSchedule refreshSchedule, + UAuthClientDiagnostics diagnostics, + IClock clock) + { + _transport = transport; + _events = events; + _tokenStore = tokenStore; + _refreshSchedule = refreshSchedule; + _diagnostics = diagnostics; + _clock = clock; + } + + public async Task ExecuteAsync(UAuthRefreshTrigger trigger, UAuthTokenSnapshot expected) + { + if (!IsCurrent(expected)) + { + return StaleRefresh(); + } + + var now = _clock.UtcNow; + + // Server-side rate limiting is scoped to the + // current authentication lifecycle. + if (_refreshThrottleEpoch != expected.Epoch) + { + _refreshThrottle = null; + _refreshNotBefore = default; + _refreshThrottleEpoch = expected.Epoch; + } + + if (_refreshThrottle is not null && now < _refreshNotBefore) + { + return _refreshThrottle with + { + RetryAfter = _refreshNotBefore - now + }; + } + + // A successful refresh without JWT rotation must + // not create an automatic refresh loop. + if (TryGetNoRotationResult(trigger, expected, now, out var deferred)) + { + return deferred!; + } + + if (!IsCurrent(expected)) + { + return StaleRefresh(); + } + + _diagnostics.MarkRefreshAttempt(trigger); + + // Raw transport: never enters request recovery. + var raw = await _transport.SendAsync(); + + ArgumentNullException.ThrowIfNull(raw); + + if (!IsCurrent(expected)) + { + return StaleRefresh(raw.Status); + } + + if (raw.Status == 429) + { + now = _clock.UtcNow; + + _refreshThrottle = new RefreshResult + { + Status = 429, + IsSuccess = false, + Outcome = RefreshOutcome.None, + ErrorCode = "rate_limited", + RetryAfter = UAuthRateLimit.ParseRetryAfter( + raw.RetryAfter, + now) + }; + + _refreshNotBefore = UAuthRateLimit.NotBefore( + now, + _refreshThrottle.RetryAfter); + + return _refreshThrottle; + } + + _refreshThrottle = null; + _refreshNotBefore = default; + + if (raw.Status == 401) + { + if (!IsCurrent(expected)) + { + return StaleRefresh(raw.Status); + } + + ClearNoRotationBackoff(); + + if (trigger != UAuthRefreshTrigger.Recovery) + { + if (!_tokenStore.TryClear(expected)) + { + return StaleRefresh(raw.Status); + } + + var clearedEpoch = unchecked( + expected.Epoch + 1); + + _refreshSchedule.MarkUnauthenticated( + expected.Epoch); + + _diagnostics.MarkRefreshReauthRequired(); + + await _events.PublishAsync( + new UAuthStateEventArgs( + UAuthStateEvent.ReauthenticationRequired, + UAuthStateEventHandlingMode.Patch, + clearedEpoch)); + } + + return new RefreshResult + { + IsSuccess = false, + Status = 401, + Outcome = RefreshOutcome.ReauthRequired + }; + } + + EnsureValidHttpStatus(raw); + + var outcome = RefreshOutcomeParser.Parse( + raw.RefreshOutcome); + + var isSuccess = + raw.Ok && raw.Status is >= 200 and < 300; + + var result = new RefreshResult + { + IsSuccess = isSuccess, + Status = raw.Status, + Outcome = outcome + }; + + if (!isSuccess) + { + return result; + } + + var accessToken = UAuthLoginCompletion.ReadAccessToken(raw); + + if (accessToken is not null) + { + if (accessToken.IsExpired(_clock.UtcNow)) + { + // Reject the invalid response without + // destroying the existing credential. + throw new UAuthProtocolException( + "Server returned an expired access token."); + } + + var sameJwt = + expected.Token is { Format: TokenFormat.Jwt } && + accessToken.Format == TokenFormat.Jwt && + string.Equals( + expected.Token.Token, + accessToken.Token, + StringComparison.Ordinal); + + if (sameJwt) + { + // The same JWT cannot acquire a new + // expiration merely through response metadata. + if (expected.Token!.ExpiresAt != accessToken.ExpiresAt) + { + throw new UAuthProtocolException( + "Server returned inconsistent expiration for the same access token."); + } + + if (!IsCurrent(expected)) + { + return StaleRefresh(raw.Status); + } + } + else + { + if (!_tokenStore.TryRotate( + expected, + accessToken)) + { + return StaleRefresh(raw.Status); + } + } + } + else if (!IsCurrent(expected)) + { + return StaleRefresh(raw.Status); + } + + var current = _tokenStore.Capture(); + + if (current.Epoch != expected.Epoch) + { + return StaleRefresh(raw.Status); + } + + _refreshSchedule.MarkRefreshed(expected); + + RecordOutcome(outcome); + + var jwtUnchanged = + expected.Token is { Format: TokenFormat.Jwt } && + current.Token is { Format: TokenFormat.Jwt } && + string.Equals( + expected.Token.Token, + current.Token.Token, + StringComparison.Ordinal); + + if (jwtUnchanged) + { + SetNoRotationBackoff(current, result); + } + else + { + ClearNoRotationBackoff(); + } + + return result; + } + + private void RecordOutcome(RefreshOutcome outcome) + { + switch (outcome) + { + case RefreshOutcome.NoOp: + _diagnostics.MarkRefreshNoOp(); + break; + + case RefreshOutcome.Touched: + _diagnostics.MarkRefreshTouched(); + break; + + case RefreshOutcome.Rotated: + _diagnostics.MarkRefreshRotated(); + break; + + case RefreshOutcome.ReauthRequired: + _diagnostics.MarkRefreshReauthRequired(); + break; + + case RefreshOutcome.Success: + _diagnostics.MarkRefreshSuccess(); + break; + } + } + + private static void EnsureValidHttpStatus(UAuthTransportResult raw) + { + if (raw.Status == 0) + { + throw new UAuthTransportException("Network error."); + } + + if (raw.Status is >= 500 and <= 599) + { + throw new UAuthTransportException($"Server error {raw.Status}.", (HttpStatusCode)raw.Status); + } + + if (raw.Status < 200 || + raw.Status is >= 300 and < 400 || + raw.Status >= 600) + { + throw new UAuthProtocolException($"Unexpected HTTP status code: {raw.Status}."); + } + } + + private bool IsCurrent(UAuthTokenSnapshot expected) + { + var current = _tokenStore.Capture(); + + return current.Epoch == expected.Epoch && current.Generation == expected.Generation; + } + + private static RefreshResult StaleRefresh(int status = 0) + { + return new RefreshResult + { + IsSuccess = false, + Status = status, + Outcome = RefreshOutcome.None, + ErrorCode = "stale_refresh" + }; + } + + private bool TryGetNoRotationResult( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot expected, + DateTimeOffset now, + out RefreshResult? result) + { + result = null; + + if (_noRotationResult is null) + { + return false; + } + + if (_noRotationEpoch != expected.Epoch || + expected.Token is not { Format: TokenFormat.Jwt } token || + !string.Equals( + _noRotationToken, + token.Token, + StringComparison.Ordinal)) + { + ClearNoRotationBackoff(); + + return false; + } + + if (now >= _noRotationNotBefore) + { + ClearNoRotationBackoff(); + + return false; + } + + // Explicit refresh and authentication recovery + // must not be blocked by automatic refresh backoff. + if (trigger is not ( + UAuthRefreshTrigger.Proactive or + UAuthRefreshTrigger.Background)) + { + return false; + } + + if (token.IsExpired(now)) + { + result = new RefreshResult + { + IsSuccess = false, + Status = 401, + Outcome = RefreshOutcome.None, + ErrorCode = "access_token_not_rotated", + RetryAfter = _noRotationNotBefore - now + }; + + return true; + } + + // The previous refresh succeeded and the existing + // JWT is still usable. Do not perform another request. + result = _noRotationResult with + { + Outcome = RefreshOutcome.NoOp + }; + + return true; + } + + private void SetNoRotationBackoff(UAuthTokenSnapshot snapshot, RefreshResult result) + { + _noRotationEpoch = snapshot.Epoch; + _noRotationToken = snapshot.Token!.Token; + _noRotationNotBefore = UAuthRateLimit.NotBefore(_clock.UtcNow, UAuthRefreshSchedule.JwtRetryInterval); + + _noRotationResult = result; + } + + private void ClearNoRotationBackoff() + { + _noRotationEpoch = null; + _noRotationToken = null; + _noRotationNotBefore = default; + _noRotationResult = null; + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshSchedule.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshSchedule.cs new file mode 100644 index 00000000..1163dcd8 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRefreshSchedule.cs @@ -0,0 +1,259 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; +using Microsoft.Extensions.Options; + +namespace CodeBeam.UltimateAuth.Client.Infrastructure; + +internal sealed class UAuthRefreshSchedule +{ + private readonly IUAuthTokenStore _tokenStore; + private readonly UAuthClientAutoRefreshOptions _options; + private readonly IClock _clock; + + private readonly object _sync = new(); + + private long? _epoch; + private DateTimeOffset? _lastSuccessfulRefreshAt; + + internal static TimeSpan JwtRetryInterval { get; } = TimeSpan.FromSeconds(10); + private long? _jwtEpoch; + private AccessToken? _scheduledJwt; + private DateTimeOffset? _jwtRefreshAt; + + public UAuthRefreshSchedule( + IUAuthTokenStore tokenStore, + IOptions options, + IClock clock) + { + _tokenStore = tokenStore; + _options = options.Value.AutoRefresh; + _clock = clock; + } + + public TimeSpan Interval => _options.Interval ?? TimeSpan.FromMinutes(5); + + public void MarkAuthenticated() + { + MarkAuthenticated(_tokenStore.Capture()); + } + + public void MarkAuthenticated(UAuthTokenSnapshot expected) + { + lock (_sync) + { + var current = _tokenStore.Capture(); + + if (current.Epoch != expected.Epoch) + { + return; + } + + if (_epoch != current.Epoch) + { + _epoch = current.Epoch; + _lastSuccessfulRefreshAt = _clock.UtcNow; + } + + UpdateJwtSchedule(current); + } + } + + public void MarkUnauthenticated() + { + lock (_sync) + { + _epoch = null; + _lastSuccessfulRefreshAt = null; + + ClearJwtSchedule(); + } + } + + public void MarkUnauthenticated(long expectedEpoch) + { + lock (_sync) + { + if (_epoch == expectedEpoch) + { + _epoch = null; + _lastSuccessfulRefreshAt = null; + } + + if (_jwtEpoch == expectedEpoch) + { + ClearJwtSchedule(); + } + } + } + + public void MarkRefreshed(UAuthTokenSnapshot expected) + { + lock (_sync) + { + var current = _tokenStore.Capture(); + + if (current.Epoch != expected.Epoch) + { + return; + } + + if (_epoch == expected.Epoch) + { + _lastSuccessfulRefreshAt = _clock.UtcNow; + } + + UpdateJwtSchedule(current); + } + } + + public bool IsAuthenticated(UAuthTokenSnapshot snapshot) + { + lock (_sync) + { + var current = _tokenStore.Capture(); + + return current.Epoch == snapshot.Epoch && + _epoch == snapshot.Epoch && + _lastSuccessfulRefreshAt is not null; + } + } + + public bool IsDue(UAuthTokenSnapshot snapshot) + { + var next = GetNextRefreshAt(snapshot); + + return next is not null && + next.Value <= _clock.UtcNow; + } + + public DateTimeOffset? GetNextRefreshAt( + UAuthTokenSnapshot snapshot) + { + lock (_sync) + { + var current = _tokenStore.Capture(); + + if (current.Epoch != snapshot.Epoch || + current.Generation != snapshot.Generation) + { + return null; + } + + if (current.Token is { Format: TokenFormat.Jwt }) + { + UpdateJwtSchedule(current); + + return _jwtRefreshAt; + } + + if (_epoch != current.Epoch || + _lastSuccessfulRefreshAt is null) + { + return null; + } + + return UAuthRateLimit.NotBefore( + _lastSuccessfulRefreshAt.Value, + Interval); + } + } + + private void UpdateJwtSchedule(UAuthTokenSnapshot snapshot) + { + if (snapshot.Token is not { Format: TokenFormat.Jwt } token) + { + ClearJwtSchedule(); + + return; + } + + // The schedule belongs to the credential itself, + // not to the last successful refresh operation. + if (_jwtEpoch == snapshot.Epoch && + _scheduledJwt is not null && + _scheduledJwt.ExpiresAt == token.ExpiresAt && + string.Equals( + _scheduledJwt.Token, + token.Token, + StringComparison.Ordinal)) + { + return; + } + + var now = _clock.UtcNow; + + var remainingLifetime = token.ExpiresAt - now; + + var threshold = _options.RefreshBeforeExpiration; + + _jwtEpoch = snapshot.Epoch; + _scheduledJwt = token; + + if (remainingLifetime <= TimeSpan.Zero) + { + _jwtRefreshAt = token.ExpiresAt; + + return; + } + + // Prevent immediately refreshing a short-lived JWT + // when the configured threshold exceeds its lifetime. + if (threshold >= remainingLifetime) + { + threshold = TimeSpan.FromTicks( + remainingLifetime.Ticks / 2); + } + + _jwtRefreshAt = token.ExpiresAt - threshold; + } + + internal DateTimeOffset GetRetryAt(UAuthTokenSnapshot snapshot) + { + var now = _clock.UtcNow; + + var retryInterval = + snapshot.Token is { Format: TokenFormat.Jwt } + ? JwtRetryInterval + : Interval; + + return UAuthRateLimit.NotBefore(now, retryInterval); + } + + internal DateTimeOffset? GetNextRefreshEligibleAt() + { + lock (_sync) + { + var current = _tokenStore.Capture(); + + if (current.Token is { Format: TokenFormat.Jwt } token) + { + // Diagnostics must not initialize or modify the credential's refresh schedule. + if (_jwtEpoch != current.Epoch || + _scheduledJwt is null || + _scheduledJwt.ExpiresAt != token.ExpiresAt || + !string.Equals(_scheduledJwt.Token, token.Token, StringComparison.Ordinal)) + { + return null; + } + + return _jwtRefreshAt; + } + + if (_epoch != current.Epoch || _lastSuccessfulRefreshAt is null) + { + return null; + } + + return UAuthRateLimit.NotBefore(_lastSuccessfulRefreshAt.Value, Interval); + } + } + + private void ClearJwtSchedule() + { + _jwtEpoch = null; + _scheduledJwt = null; + _jwtRefreshAt = null; + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRequestRecovery.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRequestRecovery.cs new file mode 100644 index 00000000..a0a17911 --- /dev/null +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthRequestRecovery.cs @@ -0,0 +1,137 @@ +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Domain; +using Microsoft.Extensions.Options; + +namespace CodeBeam.UltimateAuth.Client.Infrastructure; + +internal sealed class UAuthRequestRecovery : IUAuthRequestRecovery +{ + private readonly IUAuthTokenStore _tokenStore; + private readonly IUAuthRefreshCoordinator _coordinator; + private readonly UAuthRefreshSchedule _refreshSchedule; + private readonly UAuthClientAutoRefreshOptions _options; + private readonly IClock _clock; + + public UAuthRequestRecovery( + IUAuthTokenStore tokenStore, + IUAuthRefreshCoordinator coordinator, + UAuthRefreshSchedule refreshSchedule, + IOptions options, + IClock clock) + { + _tokenStore = tokenStore; + _coordinator = coordinator; + _refreshSchedule = refreshSchedule; + _options = options.Value.AutoRefresh; + _clock = clock; + } + + public async Task PrepareAsync(CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + + var snapshot = _tokenStore.Capture(); + + if (!_options.Proactive || !_refreshSchedule.IsDue(snapshot)) + { + return new(snapshot); + } + + var result = await _coordinator.RefreshIfCurrentAsync(UAuthRefreshTrigger.Proactive, snapshot, ct); + + ct.ThrowIfCancellationRequested(); + + var current = _tokenStore.Capture(); + + if (result.Outcome == RefreshOutcome.ReauthRequired) + { + return new(current, result); + } + + if (current.Epoch != snapshot.Epoch) + { + return new(current, AuthenticationChanged()); + } + + if (result.IsSuccess || result.ErrorCode is "refresh_not_due" or "token_changed") + { + return new(current); + } + + if (result.Status == 429) + { + if (current.Token is { } token && !token.IsExpired(_clock.UtcNow)) + { + return new(current); + } + + // Cookie-only authentication may still be valid. + if (current.Token is null && _refreshSchedule.IsAuthenticated(current)) + { + return new(current); + } + } + + return new(current, result); + } + + public async Task RecoverAsync(UAuthTokenSnapshot rejected, CancellationToken ct = default) + { + ct.ThrowIfCancellationRequested(); + + if (!_options.Reactive || rejected.Token is null) + return null; + + var current = _tokenStore.Capture(); + + if (current.Epoch != rejected.Epoch) + return null; + + // Another request already rotated the rejected token. + if (CanReplay(rejected, current)) + return current; + + if (current.Generation != rejected.Generation) + return null; + + var result = await _coordinator.RefreshIfCurrentAsync(UAuthRefreshTrigger.Reactive, rejected, ct); + + ct.ThrowIfCancellationRequested(); + + current = _tokenStore.Capture(); + + if (current.Epoch != rejected.Epoch) + return null; + + if (!result.IsSuccess && result.ErrorCode != "token_changed") + { + return null; + } + + return CanReplay(rejected, current) + ? current + : null; + } + + private bool CanReplay(UAuthTokenSnapshot rejected, UAuthTokenSnapshot current) + { + return current.Epoch == rejected.Epoch && + current.Generation != rejected.Generation && + current.Token is not null && + !current.Token.IsExpired(_clock.UtcNow) && + !string.Equals(current.Token.Token, rejected.Token?.Token, StringComparison.Ordinal); + } + + private static RefreshResult AuthenticationChanged() + { + return new RefreshResult + { + IsSuccess = false, + Status = 401, + Outcome = RefreshOutcome.None, + ErrorCode = "authentication_changed" + }; + } +} diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthResultMapper.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthResultMapper.cs index 0ca40000..4566d147 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthResultMapper.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthResultMapper.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Errors; +using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Core.Contracts; using System.Net; using System.Text.Json; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthUrlBuilder.cs b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthUrlBuilder.cs index 4b6de185..0b9b1405 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthUrlBuilder.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Infrastructure/UAuthUrlBuilder.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Client.Options; namespace CodeBeam.UltimateAuth.Client.Infrastructure; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientAutoRefreshOptions.cs b/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientAutoRefreshOptions.cs index eebd7e3f..99f515d6 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientAutoRefreshOptions.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientAutoRefreshOptions.cs @@ -7,17 +7,37 @@ public sealed class UAuthClientAutoRefreshOptions { /// - /// Enables background refresh coordination. - /// Default: true for BlazorServer, false otherwise. + /// Enables independent background refresh coordination. + /// Default is false. /// - public bool Enabled { get; set; } = true; + public bool Background { get; set; } /// - /// Interval for background refresh attempts. - /// This is a UX / keep-alive setting, NOT a security policy. + /// Enables automatic authentication recovery following a recoverable authentication failure. + /// Enabled by default. + /// + public bool Reactive { get; set; } = true; + + /// + /// Enables expiration-aware access token refresh before authenticated requests. + /// Enabled by default. + /// + public bool Proactive { get; set; } = true; + + /// + /// Defines the refresh eligibility interval when no managed JWT access token is available. + /// Applies to proactive and background refresh. + /// Defaults to five minutes after client configuration. /// public TimeSpan? Interval { get; set; } + /// + /// Defines how long before JWT expiration authentication becomes eligible for refresh. + /// Applies to proactive and background refresh. + /// Defaults to one minute. + /// + public TimeSpan RefreshBeforeExpiration { get; set; } = TimeSpan.FromMinutes(1); + // TODO: Future enhancement: Add jitter to avoid synchronized refresh storms in multi-tab scenarios. ///// ///// Optional jitter to avoid synchronized refresh storms. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientMultiTenantOptions.cs b/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientMultiTenantOptions.cs index ee273691..283c2b1b 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientMultiTenantOptions.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Options/UAuthClientMultiTenantOptions.cs @@ -1,6 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; - -namespace CodeBeam.UltimateAuth.Client.Options; +namespace CodeBeam.UltimateAuth.Client.Options; /// /// Options for multi-tenant support in the UAuth client. diff --git a/src/client/CodeBeam.UltimateAuth.Client/Runtime/UAuthClientProductInfoProvider.cs b/src/client/CodeBeam.UltimateAuth.Client/Runtime/UAuthClientProductInfoProvider.cs index 512d2da5..3d2b5d00 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Runtime/UAuthClientProductInfoProvider.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Runtime/UAuthClientProductInfoProvider.cs @@ -20,7 +20,7 @@ public UAuthClientProductInfoProvider(IOptions options) StartedAt = DateTimeOffset.UtcNow, ApplicationProfile = opts.ApplicationProfile, - AutoRefreshEnabled = opts.AutoRefresh.Enabled, + AutoRefreshEnabled = opts.AutoRefresh.Background, RefreshInterval = opts.AutoRefresh.Interval, ReauthBehavior = opts.Reauth.Behavior, diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/Abstractions/IFlowClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/Abstractions/IFlowClient.cs index 25493916..c68df88f 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/Abstractions/IFlowClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/Abstractions/IFlowClient.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Users.Contracts; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthAuthorizationClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthAuthorizationClient.cs index 2281ecdf..24d60d81 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthAuthorizationClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthAuthorizationClient.cs @@ -1,4 +1,5 @@ using CodeBeam.UltimateAuth.Authorization.Contracts; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -25,33 +26,33 @@ public UAuthAuthorizationClient(IUAuthRequestClient request, IUAuthClientEvents public async Task> CheckAsync(AuthorizationCheckRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/authorization/check"), request); + var raw = await _request.SendJsonAsync(Url("/me/authorization/check"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> GetMyRolesAsync(PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url("/me/authorization/roles/get"), request); + var raw = await _request.SendJsonAsync(Url("/me/authorization/roles/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> GetMyPermissionsAsync() { - var raw = await _request.SendJsonAsync(Url("/me/authorization/permissions/get"), new { }); + var raw = await _request.SendJsonAsync(Url("/me/authorization/permissions/get"), new { }, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> GetUserRolesAsync(UserKey userKey, PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{userKey.Value}/roles/get"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{userKey.Value}/roles/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task AssignRoleToUserAsync(AssignRoleRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{request.UserKey.Value}/roles/assign"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{request.UserKey.Value}/roles/assign"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); @@ -65,7 +66,7 @@ public async Task AssignRoleToUserAsync(AssignRoleRequest request) public async Task RemoveRoleFromUserAsync(RemoveRoleRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{request.UserKey.Value}/roles/remove"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/users/{request.UserKey.Value}/roles/remove"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); @@ -79,19 +80,19 @@ public async Task RemoveRoleFromUserAsync(RemoveRoleRequest request public async Task> CreateRoleAsync(CreateRoleRequest request) { - var raw = await _request.SendJsonAsync(Url("/admin/authorization/roles/create"), request); + var raw = await _request.SendJsonAsync(Url("/admin/authorization/roles/create"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task>> QueryRolesAsync(RoleQuery request) { - var raw = await _request.SendJsonAsync(Url("/admin/authorization/roles/query"), request); + var raw = await _request.SendJsonAsync(Url("/admin/authorization/roles/query"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } public async Task RenameRoleAsync(RenameRoleRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.Id.Value}/rename"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.Id.Value}/rename"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -104,7 +105,7 @@ public async Task RenameRoleAsync(RenameRoleRequest request) public async Task SetRolePermissionsAsync(SetRolePermissionsRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.RoleId.Value}/permissions"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.RoleId.Value}/permissions"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -117,7 +118,7 @@ public async Task SetRolePermissionsAsync(SetRolePermissionsRequest public async Task> DeleteRoleAsync(DeleteRoleRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.Id.Value}/delete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/authorization/roles/{request.Id.Value}/delete"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.FromJson(raw); if (result.IsSuccess) diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthCredentialClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthCredentialClient.cs index 7ee1071a..95659f8b 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthCredentialClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthCredentialClient.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Core.Contracts; @@ -25,13 +26,13 @@ public UAuthCredentialClient(IUAuthRequestClient request, IUAuthClientEvents eve public async Task> AddMyAsync(AddCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/credentials/add"), request); + var raw = await _request.SendJsonAsync(Url("/me/credentials/add"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> ChangeMyAsync(ChangeCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/credentials/change"), request); + var raw = await _request.SendJsonAsync(Url("/me/credentials/change"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.FromJson(raw); if (result.IsSuccess) @@ -45,7 +46,7 @@ await _events.PublishAsync( public async Task RevokeMyAsync(RevokeCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/credentials/revoke"), request); + var raw = await _request.SendJsonAsync(Url("/me/credentials/revoke"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -80,37 +81,37 @@ await _events.PublishAsync( public async Task> AddUserAsync(UserKey userKey, AddCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/add"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/add"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> ChangeUserAsync(UserKey userKey, ChangeCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/change"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/change"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task RevokeUserAsync(UserKey userKey, RevokeCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/revoke"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/revoke"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task> BeginResetUserAsync(UserKey userKey, BeginResetCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/reset/begin"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/reset/begin"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> CompleteResetUserAsync(UserKey userKey, CompleteResetCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/reset/complete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/reset/complete"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task DeleteUserAsync(UserKey userKey, DeleteCredentialRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/delete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/credentials/delete"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs index 93c6a223..0899ad6a 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthFlowClient.cs @@ -1,6 +1,4 @@ using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Extensions; @@ -26,21 +24,25 @@ internal class UAuthFlowClient : IFlowClient private readonly IClientDeviceProvider _clientDeviceProvider; private readonly IReturnUrlProvider _returnUrlProvider; private readonly UAuthClientOptions _options; - private readonly UAuthClientDiagnostics _diagnostics; private readonly IUAuthTokenStore _tokenStore; - - private DateTimeOffset _refreshNotBefore; - private RefreshResult? _refreshThrottle; - - public UAuthFlowClient(IUAuthRequestClient post, IUAuthClientEvents events, IClientDeviceProvider clientDeviceProvider, IReturnUrlProvider returnUrlProvider, IOptions options, UAuthClientDiagnostics diagnostics, IUAuthTokenStore tokenStore) + private readonly IUAuthRefreshCoordinator _refreshCoordinator; + + public UAuthFlowClient( + IUAuthRequestClient post, + IUAuthClientEvents events, + IClientDeviceProvider clientDeviceProvider, + IReturnUrlProvider returnUrlProvider, + IOptions options, + IUAuthTokenStore tokenStore, + IUAuthRefreshCoordinator refreshCoordinator) { _post = post; _events = events; _clientDeviceProvider = clientDeviceProvider; _returnUrlProvider = returnUrlProvider; _options = options.Value; - _diagnostics = diagnostics; _tokenStore = tokenStore; + _refreshCoordinator = refreshCoordinator; } private string Url(string path) => UAuthUrlBuilder.Build(_options.Endpoints.BasePath, path, _options.MultiTenant); @@ -245,12 +247,14 @@ public async Task LogoutAsync(bool navigate = true) public Task RefreshAsync(bool isAuto = false) { - return RefreshCoreAsync(isAuto, isRecovery: false); + return _refreshCoordinator.RefreshAsync(isAuto + ? UAuthRefreshTrigger.Background + : UAuthRefreshTrigger.Manual); } public Task RecoverAsync() { - return RefreshCoreAsync(isAuto: true, isRecovery: true); + return _refreshCoordinator.RefreshAsync(UAuthRefreshTrigger.Recovery); } @@ -268,7 +272,6 @@ public async Task ValidateAsync() if (accessToken is not null && accessToken.IsExpired(DateTimeOffset.UtcNow)) { - _tokenStore.Clear(); accessToken = null; } @@ -571,116 +574,6 @@ public async Task LogoutAllUserDevicesAsync(UserKey userKey) return UAuthResultMapper.From(raw); } - - private async Task RefreshCoreAsync(bool isAuto, bool isRecovery) - { - if (!isAuto) - _diagnostics.MarkManualRefresh(); - - var now = DateTimeOffset.UtcNow; - - if (_refreshThrottle is not null && now < _refreshNotBefore) - return _refreshThrottle with { RetryAfter = _refreshNotBefore - now }; - - var raw = await _post.SendFormAsync(Url(_options.Endpoints.Refresh)); - if (raw.Status == 429) - { - _refreshThrottle = new RefreshResult - { - Status = 429, - IsSuccess = false, - Outcome = RefreshOutcome.None, - ErrorCode = "rate_limited", - RetryAfter = UAuthRateLimit.ParseRetryAfter(raw.RetryAfter, DateTimeOffset.UtcNow) - }; - _refreshNotBefore = UAuthRateLimit.NotBefore(DateTimeOffset.UtcNow, _refreshThrottle.RetryAfter); - return _refreshThrottle; - } - _refreshThrottle = null; - - if (raw.Status == 401) - { - if (!isRecovery) - { - _tokenStore.Clear(); - _diagnostics.MarkRefreshReauthRequired(); - - await _events.PublishAsync( - new UAuthStateEventArgsEmpty( - UAuthStateEvent.ReauthenticationRequired, - UAuthStateEventHandlingMode.Patch)); - } - - return new RefreshResult - { - IsSuccess = false, - Status = 401, - Outcome = RefreshOutcome.ReauthRequired - }; - } - - EnsureValidHttpStatus(raw); - - var outcome = RefreshOutcomeParser.Parse(raw.RefreshOutcome); - var isSuccess = raw.Status is >= 200 and < 300 && raw.Ok; - - if (isSuccess) - { - var accessToken = UAuthLoginCompletion.ReadAccessToken(raw); - - if (accessToken is not null) - { - if (accessToken.IsExpired(DateTimeOffset.UtcNow)) - { - _tokenStore.Clear(); - - throw new UAuthProtocolException("Server returned an expired access token."); - } - - _tokenStore.Replace(accessToken); - } - } - - // Never record a successful refresh outcome - // for a failed HTTP response. - if (isSuccess) - { - switch (outcome) - { - case RefreshOutcome.NoOp: - _diagnostics.MarkRefreshNoOp(); - break; - - case RefreshOutcome.Touched: - _diagnostics.MarkRefreshTouched(); - break; - - case RefreshOutcome.Rotated: - _diagnostics.MarkRefreshRotated(); - break; - - case RefreshOutcome.ReauthRequired: - _diagnostics.MarkRefreshReauthRequired(); - break; - - case RefreshOutcome.Success: - _diagnostics.MarkRefreshSuccess(); - break; - } - } - else if (outcome == RefreshOutcome.ReauthRequired) - { - _diagnostics.MarkRefreshReauthRequired(); - } - - return new RefreshResult - { - IsSuccess = isSuccess, - Status = raw.Status, - Outcome = outcome - }; - } - private void EnsureCanPost() { var canPost = ClientLoginCapabilities.CanPostCredentials(_options.ApplicationProfile); diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthResourceClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthResourceClient.cs index a9998c63..28c00992 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthResourceClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthResourceClient.cs @@ -1,5 +1,5 @@ using System.Text.Json; -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Core.Contracts; diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthSessionClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthSessionClient.cs index 116dea77..cbd4c36d 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthSessionClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthSessionClient.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Core.Contracts; @@ -27,7 +28,7 @@ private string Url(string path) public async Task>> GetMyChainsAsync(PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url("/me/sessions/chains"), request); + var raw = await _request.SendJsonAsync(Url("/me/sessions/chains"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } @@ -39,7 +40,7 @@ public async Task> GetMyChainDetailAsync(Session public async Task> RevokeMyChainAsync(SessionChainId chainId) { - var raw = await _request.SendJsonAsync(Url($"/me/sessions/chains/{chainId.Value}/revoke")); + var raw = await _request.SendJsonAsync(Url($"/me/sessions/chains/{chainId.Value}/revoke"), null, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.FromJson(raw); if (result.IsSuccess && result.Value?.CurrentChain == true) @@ -73,7 +74,7 @@ public async Task RevokeAllMyChainsAsync() public async Task>> GetUserChainsAsync(UserKey userKey, PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/sessions/chains"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/sessions/chains"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserClient.cs index b204503d..174f08bd 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserClient.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Core.Contracts; @@ -26,13 +27,13 @@ public UAuthUserClient(IUAuthRequestClient request, IUAuthClientEvents events, I public async Task> GetMeAsync(GetProfileRequest? request = null) { request ??= new GetProfileRequest(); - var raw = await _request.SendJsonAsync(Url("/me/profile/get"), request); + var raw = await _request.SendJsonAsync(Url("/me/profile/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task UpdateMyProfileAsync(UpdateProfileRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/profile/update"), request); + var raw = await _request.SendJsonAsync(Url("/me/profile/update"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -46,7 +47,7 @@ await _events.PublishAsync( public async Task DeleteMeAsync() { - var raw = await _request.SendJsonAsync(Url("/me/delete")); + var raw = await _request.SendJsonAsync(Url("/me/delete"), null, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -60,7 +61,7 @@ public async Task DeleteMeAsync() public async Task>> QueryAsync(UserQuery query) { query ??= new UserQuery(); - var raw = await _request.SendJsonAsync(Url("/admin/users/query"), query); + var raw = await _request.SendJsonAsync(Url("/admin/users/query"), query, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } @@ -73,14 +74,14 @@ public async Task>> GetByKeysAsync(IReadO UserKeys = userKeys.ToArray() }; - var raw = await _request.SendJsonAsync(Url("/admin/users/get-by-keys"), request); + var raw = await _request.SendJsonAsync(Url("/admin/users/get-by-keys"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } public async Task CreateMyProfileAsync(CreateProfileRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/profile/create"), request); + var raw = await _request.SendJsonAsync(Url("/me/profile/create"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); @@ -95,19 +96,19 @@ await _events.PublishAsync( public async Task CreateUserProfileAsync(UserKey userKey, CreateProfileRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/create"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/create"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task> CreateAsync(CreateUserRequest request) { - var raw = await _request.SendJsonAsync(Url("/users/create"), request); + var raw = await _request.SendJsonAsync(Url("/users/create"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task DeleteMyProfileAsync(DeleteProfileRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/profile/delete"), request); + var raw = await _request.SendJsonAsync(Url("/me/profile/delete"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); @@ -122,19 +123,19 @@ await _events.PublishAsync( public async Task DeleteUserProfileAsync(UserKey userKey, DeleteProfileRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/delete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/delete"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task> CreateAsAdminAsync(CreateUserRequest request) { - var raw = await _request.SendJsonAsync(Url("/admin/users/create"), request); + var raw = await _request.SendJsonAsync(Url("/admin/users/create"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> ChangeMyStatusAsync(ChangeUserStatusSelfRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/status"), request); + var raw = await _request.SendJsonAsync(Url("/me/status"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.FromJson(raw); if (result.IsSuccess) @@ -148,26 +149,26 @@ await _events.PublishAsync( public async Task> ChangeUserStatusAsync(UserKey userKey, ChangeUserStatusAdminRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/status"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/status"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> DeleteUserAsync(UserKey userKey, DeleteUserRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/delete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/delete"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task> GetUserAsync(UserKey userKey, GetProfileRequest? request = null) { request = request ?? new GetProfileRequest(); - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/get"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } public async Task UpdateUserProfileAsync(UserKey userKey, UpdateProfileRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/update"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/profile/update"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } @@ -176,7 +177,7 @@ public async Task> GetAuthenticationLocko { ArgumentNullException.ThrowIfNull(request); - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/authentication/lockout/get"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/authentication/lockout/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } @@ -184,7 +185,7 @@ public async Task> UnlockAuthenticationA { ArgumentNullException.ThrowIfNull(request); - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/authentication/unlock"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/authentication/unlock"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson(raw); } } diff --git a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserIdentifierClient.cs b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserIdentifierClient.cs index 01ea8d27..b506ab51 100644 --- a/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserIdentifierClient.cs +++ b/src/client/CodeBeam.UltimateAuth.Client/Services/UAuthUserIdentifierClient.cs @@ -1,4 +1,5 @@ -using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Core.Contracts; @@ -26,13 +27,13 @@ public UAuthUserIdentifierClient(IUAuthRequestClient request, IUAuthClientEvents public async Task>> GetMyAsync(PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url("/me/identifiers/get"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } public async Task AddMyAsync(AddUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/add"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/add"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -46,7 +47,7 @@ await _events.PublishAsync( public async Task UpdateMyAsync(UpdateUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/update"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/update"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -58,7 +59,7 @@ public async Task UpdateMyAsync(UpdateUserIdentifierRequest request public async Task SetMyPrimaryAsync(SetPrimaryUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/set-primary"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/set-primary"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -70,7 +71,7 @@ public async Task SetMyPrimaryAsync(SetPrimaryUserIdentifierRequest public async Task UnsetMyPrimaryAsync(UnsetPrimaryUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/unset-primary"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/unset-primary"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -82,7 +83,7 @@ public async Task UnsetMyPrimaryAsync(UnsetPrimaryUserIdentifierReq public async Task VerifyMyAsync(VerifyUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/verify"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/verify"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -94,7 +95,7 @@ public async Task VerifyMyAsync(VerifyUserIdentifierRequest request public async Task DeleteMyAsync(DeleteUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url("/me/identifiers/delete"), request); + var raw = await _request.SendJsonAsync(Url("/me/identifiers/delete"), request, UAuthRequestAuthentication.Recoverable); var result = UAuthResultMapper.From(raw); if (result.IsSuccess) @@ -107,43 +108,43 @@ public async Task DeleteMyAsync(DeleteUserIdentifierRequest request public async Task>> GetUserAsync(UserKey userKey, PageRequest? request = null) { request ??= new PageRequest(); - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/get"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/get"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.FromJson>(raw); } public async Task AddUserAsync(UserKey userKey, AddUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/add"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/add"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task UpdateUserAsync(UserKey userKey, UpdateUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/update"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/update"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task SetUserPrimaryAsync(UserKey userKey, SetPrimaryUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/set-primary"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/set-primary"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task UnsetUserPrimaryAsync(UserKey userKey, UnsetPrimaryUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/unset-primary"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/unset-primary"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task VerifyUserAsync(UserKey userKey, VerifyUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/verify"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/verify"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } public async Task DeleteUserAsync(UserKey userKey, DeleteUserIdentifierRequest request) { - var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/delete"), request); + var raw = await _request.SendJsonAsync(Url($"/admin/users/{userKey.Value}/identifiers/delete"), request, UAuthRequestAuthentication.Recoverable); return UAuthResultMapper.From(raw); } diff --git a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/ManagementTransportTests.cs b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/ManagementTransportTests.cs index 81eb8c7b..1fd1151d 100644 --- a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/ManagementTransportTests.cs +++ b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/ManagementTransportTests.cs @@ -1,5 +1,5 @@ using Bunit; -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.IdentityLab.Components.Pages; using CodeBeam.UltimateAuth.IdentityLab.Contracts; using CodeBeam.UltimateAuth.IdentityLab.Services; @@ -30,7 +30,7 @@ public async Task Scan_uses_browser_transport_and_renders_returned_snapshot() [Fact] public async Task Client_rejects_failed_transport_without_exposing_response_details() { - var requests = new Mock(); + var requests = new Mock(); requests.Setup(x => x.SendJsonAsync(It.IsAny(), null, It.IsAny())) .ReturnsAsync(new UAuthTransportResult { Status = 500, Body = JsonSerializer.SerializeToElement("private diagnostic") }); var error = await Assert.ThrowsAsync(() => diff --git a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.ApplicationPages.cs b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.ApplicationPages.cs index 6c410caf..9c4c1b24 100644 --- a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.ApplicationPages.cs +++ b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.ApplicationPages.cs @@ -85,7 +85,7 @@ public void AddAdminServices() public void AddDemoStoreServices() { Requests.Setup(x => x.SendJsonAsync("/api/lab/manage/demo-permissions", null, It.IsAny())) - .ReturnsAsync(new CodeBeam.UltimateAuth.Client.Contracts.UAuthTransportResult + .ReturnsAsync(new CodeBeam.UltimateAuth.Client.UAuthTransportResult { Ok = true, Status = 200, Body = System.Text.Json.JsonSerializer.SerializeToElement(Array.Empty()) }); diff --git a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.cs b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.cs index b2d073f1..58cb16d9 100644 --- a/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.cs +++ b/tests/CodeBeam.UltimateAuth.IdentityLab.Tests/Rendering/PageRenderContext.cs @@ -34,7 +34,7 @@ namespace CodeBeam.UltimateAuth.IdentityLab.Tests.Rendering; internal sealed partial class PageRenderContext : BunitContext { - public Mock Requests { get; } = new(MockBehavior.Strict); + public Mock Requests { get; } = new(MockBehavior.Strict); public Mock Client { get; } = new(MockBehavior.Strict); public Mock Sessions { get; } = new(MockBehavior.Strict); public Mock Authorization { get; } = new(MockBehavior.Strict); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/ClientRateLimitingIntegrationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/ClientRateLimitingIntegrationTests.cs index 138f2f7d..2a12586b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/ClientRateLimitingIntegrationTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/ClientRateLimitingIntegrationTests.cs @@ -1,12 +1,9 @@ using System.Net; -using System.Net.Http.Json; using System.Text.Json; using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Extensions; -using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Core.Abstractions; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; @@ -68,8 +65,24 @@ public async Task NativeRefresh429PreservesCredentials_AndSuppressesImmediateRef Assert.Equal("rate_limited", throttle.ErrorCode); Assert.Equal(RefreshOutcome.None, throttle.Outcome); Assert.Equal(credential, http.DefaultRequestHeaders.GetValues("Cookie").Single()); + // A manual refresh bypasses scheduling, but must honor throttling. + var suppressed = await flow.RefreshAsync(); + + Assert.False(suppressed.IsSuccess); + Assert.Equal(429, suppressed.Status); + Assert.Equal("rate_limited", suppressed.ErrorCode); + Assert.Equal(RefreshOutcome.None, suppressed.Outcome); + + Assert.Equal(2, transport.Count); + + // Automatic refresh must not produce another HTTP request either. await flow.RefreshAsync(isAuto: true); + Assert.Equal(2, transport.Count); + + Assert.Equal( + credential, + http.DefaultRequestHeaders.GetValues("Cookie").Single()); var session = await CsrfTestClient.PostAsync(http, "/auth/validate", null); Assert.Equal(HttpStatusCode.OK, session.StatusCode); Assert.True((await session.Content.ReadFromJsonAsync(cancellationToken: TestContext.Current.CancellationToken))!.IsValid); @@ -90,20 +103,37 @@ private static async Task Login(AuthServerFactory factory, Integrati private static ServiceProvider ClientServices(AuthServerFactory factory, HttpTransport transport) { var services = new ServiceCollection(); + services.AddLogging(); - services.AddSingleton(new ConfigurationBuilder().Build()); - services.AddUltimateAuthClient(o => { o.ApplicationProfile = UAuthApplicationProfile.BlazorServer; o.AutoDetectApplicationProfile = false; }); + + services.AddSingleton( + new ConfigurationBuilder().Build()); + + services.AddUltimateAuthClient(o => + { + o.ApplicationProfile = UAuthApplicationProfile.BlazorServer; + o.AutoDetectApplicationProfile = false; + }); + services.AddSingleton(); services.AddSingleton(factory.Clock); + services.AddSingleton(transport); services.AddSingleton(transport); + services.AddSingleton(transport); services.AddSingleton(transport); services.AddSingleton(transport); + return services.BuildServiceProvider(); } // Thin HTTP test adapter: public SDK contracts against the real auth host and native middleware. - private sealed class HttpTransport(HttpClient http) : IUAuthRequestClient, IUAuthResourceRequestClient, IClientDeviceProvider, IReturnUrlProvider + private sealed class HttpTransport(HttpClient http) : + IUAuthRequestClient, + IUAuthResourceRequestClient, + IUAuthRefreshTransport, + IClientDeviceProvider, + IReturnUrlProvider { internal int Count { get; private set; } public Task NavigateAsync(string endpoint, IDictionary? form = null, CancellationToken ct = default) => throw new NotSupportedException(); @@ -129,6 +159,13 @@ public async Task SendJsonAsync(string endpoint, object? p using var response = await CsrfTestClient.PostJsonAsync(http, endpoint, payload); return await Read(response, ct); } + public Task SendAsync(CancellationToken ct = default) + { + return SendFormAsync( + "/auth/refresh", + form: null, + ct: ct); + } public Task GetLoginTransportAsync(string endpoint, CancellationToken ct = default) { diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/CsrfTestClient.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/CsrfTestClient.cs index 2aca4bdd..a21bf62a 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/CsrfTestClient.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/CsrfTestClient.cs @@ -94,7 +94,17 @@ private static async Task SendAsync( public static async Task SendAsync(HttpClient client, HttpRequestMessage request, string tokenUrl = "/auth/antiforgery/token") { - using var tokenResponse = await client.GetAsync(tokenUrl); + using var tokenRequest = new HttpRequestMessage( + HttpMethod.Get, + tokenUrl); + + // Preserve the authentication context of the original request. + CopyHeader("Authorization"); + CopyHeader("uas"); + CopyHeader("Cookie"); + + using var tokenResponse = await client.SendAsync(tokenRequest); + tokenResponse.EnsureSuccessStatusCode(); var token = await tokenResponse.Content @@ -108,6 +118,8 @@ public static async Task SendAsync(HttpClient client, HttpR "Invalid antiforgery token response."); } + request.Headers.Remove(token.HeaderName); + request.Headers.TryAddWithoutValidation( token.HeaderName, token.RequestToken); @@ -122,11 +134,13 @@ public static async Task SendAsync(HttpClient client, HttpR var existingCookies = request.Headers.TryGetValues("Cookie", out var requestCookies) ? string.Join("; ", requestCookies) - : client.DefaultRequestHeaders.TryGetValues("Cookie", out var clientCookies) + : client.DefaultRequestHeaders.TryGetValues( + "Cookie", out var clientCookies) ? string.Join("; ", clientCookies) : string.Empty; request.Headers.Remove("Cookie"); + request.Headers.TryAddWithoutValidation( "Cookie", string.IsNullOrWhiteSpace(existingCookies) @@ -134,5 +148,15 @@ public static async Task SendAsync(HttpClient client, HttpR : $"{existingCookies}; {antiforgeryCookie}"); return await client.SendAsync(request); + + void CopyHeader(string name) + { + if (request.Headers.TryGetValues(name, out var values)) + { + tokenRequest.Headers.TryAddWithoutValidation( + name, + values); + } + } } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs index 2f8f0765..6f728bf9 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs @@ -2452,8 +2452,9 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive factory.Clock.Reset(); - var user = await factory.CreateLoginUserAsync( - ct: TestContext.Current.CancellationToken); + var ct = TestContext.Current.CancellationToken; + + var user = await factory.CreateLoginUserAsync(ct: ct); using var client = CreateClient( factory, @@ -2479,18 +2480,18 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive sessionId.Should().NotBeNullOrWhiteSpace(); refreshToken.Should().NotBeNullOrWhiteSpace(); - // First refresh using MAUI header credentials. + // First refresh using configured header credentials. using var firstRequest = new HttpRequestMessage( HttpMethod.Post, "/auth/refresh"); firstRequest.Headers.TryAddWithoutValidation( - "X-UAuth-Session", - sessionId); + "uas", + $"Bearer {sessionId}"); firstRequest.Headers.TryAddWithoutValidation( - "X-Refresh-Token", - refreshToken); + "uar", + $"Bearer {refreshToken}"); using var first = await CsrfTestClient.SendAsync( client, @@ -2498,7 +2499,7 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive first.StatusCode.Should().Be( HttpStatusCode.NoContent, - $"first refresh failed: {await first.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)}"); + $"first refresh failed: {await first.Content.ReadAsStringAsync(ct)}"); var rotatedRefreshToken = ReadCredential(first, "uar"); @@ -2514,12 +2515,12 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive "/auth/refresh"); secondRequest.Headers.TryAddWithoutValidation( - "X-UAuth-Session", - nextSessionId); + "uas", + $"Bearer {nextSessionId}"); secondRequest.Headers.TryAddWithoutValidation( - "X-Refresh-Token", - rotatedRefreshToken); + "uar", + $"Bearer {rotatedRefreshToken}"); using var second = await CsrfTestClient.SendAsync( client, @@ -2527,7 +2528,13 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive second.StatusCode.Should().Be( HttpStatusCode.NoContent, - $"second refresh failed: {await second.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)}"); + $"second refresh failed: {await second.Content.ReadAsStringAsync(ct)}"); + + var secondRotatedRefreshToken = ReadCredential(second, "uar"); + + secondRotatedRefreshToken.Should().NotBeNullOrWhiteSpace(); + secondRotatedRefreshToken.Should().NotBe(rotatedRefreshToken); + secondRotatedRefreshToken.Should().NotBe(refreshToken); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthLoginFormSubmissionTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthLoginFormSubmissionTests.cs index 5f50a1e4..91d4e3b1 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthLoginFormSubmissionTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthLoginFormSubmissionTests.cs @@ -3,7 +3,6 @@ using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Blazor; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthRequestClientTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthRequestClientTests.cs index d39c2669..bc2ddf01 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthRequestClientTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/Blazor/UAuthRequestClientTests.cs @@ -2,7 +2,7 @@ using Bunit; using Bunit.TestDoubles; using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientDiagnosticsTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientDiagnosticsTests.cs index be8b92c9..4a1c52e4 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientDiagnosticsTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientDiagnosticsTests.cs @@ -1,85 +1,432 @@ -using System; -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Diagnostics; -using Xunit; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Tests.Unit.Helpers; +using Microsoft.Extensions.Options; namespace CodeBeam.UltimateAuth.Tests.Unit; public class ClientDiagnosticsTests { + // -------------------------------------------------------- + // Initial state + // -------------------------------------------------------- + [Fact] - public void MarkStarted_ShouldSetStartedAt_AndIncrementCounter() + public void InitialState_ShouldBeEmpty() { var diagnostics = new UAuthClientDiagnostics(); + + Assert.Null(diagnostics.StartedAt); + Assert.Null(diagnostics.StoppedAt); + Assert.Null(diagnostics.TerminatedAt); + Assert.Null(diagnostics.TerminationReason); + Assert.Null(diagnostics.RunningDuration); + + Assert.False(diagnostics.IsRunning); + Assert.False(diagnostics.IsStopped); + Assert.False(diagnostics.IsTerminated); + + Assert.Equal(0, diagnostics.StartCount); + Assert.Equal(0, diagnostics.StopCount); + Assert.Equal(0, diagnostics.TerminatedCount); + + Assert.Equal(0, diagnostics.RefreshAttemptCount); + Assert.Equal(0, diagnostics.ManualRefreshCount); + Assert.Equal(0, diagnostics.BackgroundRefreshCount); + Assert.Equal(0, diagnostics.ProactiveRefreshCount); + Assert.Equal(0, diagnostics.ReactiveRefreshCount); + Assert.Equal(0, diagnostics.RecoveryRefreshCount); + Assert.Equal(0, diagnostics.AutomaticRefreshCount); + + Assert.Equal(0, diagnostics.RefreshTouchedCount); + Assert.Equal(0, diagnostics.RefreshRotatedCount); + Assert.Equal(0, diagnostics.RefreshNoOpCount); + Assert.Equal(0, diagnostics.RefreshReauthRequiredCount); + Assert.Equal(0, diagnostics.RefreshSuccessCount); + + Assert.Null(diagnostics.NextAutomaticRefreshAt); + Assert.Null(diagnostics.NextRefreshEligibleAt); + } + + // -------------------------------------------------------- + // Lifecycle + // -------------------------------------------------------- + + [Fact] + public void MarkStarted_ShouldSetRunningState() + { + var diagnostics = new UAuthClientDiagnostics(); + diagnostics.MarkStarted(); Assert.NotNull(diagnostics.StartedAt); + Assert.Null(diagnostics.StoppedAt); Assert.Equal(1, diagnostics.StartCount); + + Assert.True(diagnostics.IsRunning); + Assert.False(diagnostics.IsStopped); Assert.False(diagnostics.IsTerminated); } [Fact] - public void MarkStopped_ShouldSetStoppedAt_AndIncrementCounter() + public void MarkStopped_ShouldClearBackgroundSchedule() { var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkStarted(); + + diagnostics.SetNextAutomaticRefresh( + DateTimeOffset.UtcNow.AddMinutes(5)); + diagnostics.MarkStopped(); Assert.NotNull(diagnostics.StoppedAt); Assert.Equal(1, diagnostics.StopCount); + + Assert.True(diagnostics.IsStopped); + Assert.False(diagnostics.IsRunning); + Assert.False(diagnostics.IsTerminated); + + Assert.Null(diagnostics.NextAutomaticRefreshAt); + } + + [Fact] + public void MarkTerminated_ShouldSetTerminationState() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkStarted(); + + diagnostics.SetNextAutomaticRefresh( + DateTimeOffset.UtcNow.AddMinutes(5)); + + diagnostics.MarkTerminated( + CoordinatorTerminationReason.ReauthRequired); + + Assert.True(diagnostics.IsTerminated); + Assert.False(diagnostics.IsRunning); + + Assert.NotNull(diagnostics.TerminatedAt); + + Assert.Equal( + CoordinatorTerminationReason.ReauthRequired, + diagnostics.TerminationReason); + + Assert.Equal(1, diagnostics.TerminatedCount); + Assert.Null(diagnostics.NextAutomaticRefreshAt); + } + + [Fact] + public void MarkTerminated_ShouldCountRepeatedTerminations() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkTerminated( + CoordinatorTerminationReason.ReauthRequired); + + diagnostics.MarkTerminated( + CoordinatorTerminationReason.ReauthRequired); + + Assert.True(diagnostics.IsTerminated); + Assert.Equal(2, diagnostics.TerminatedCount); + } + + [Fact] + public void MarkStarted_AfterStop_ShouldRestoreRunningState() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkStarted(); + diagnostics.MarkStopped(); + diagnostics.MarkStarted(); + + Assert.True(diagnostics.IsRunning); + Assert.False(diagnostics.IsStopped); + Assert.False(diagnostics.IsTerminated); + + Assert.Null(diagnostics.StoppedAt); + + Assert.Equal(2, diagnostics.StartCount); + Assert.Equal(1, diagnostics.StopCount); } [Fact] - public void MarkManualRefresh_ShouldIncrementManualAndTotalCounters() + public void MarkStarted_AfterTermination_ShouldResetTerminationState() { var diagnostics = new UAuthClientDiagnostics(); - diagnostics.MarkManualRefresh(); + + diagnostics.MarkStarted(); + + diagnostics.MarkTerminated( + CoordinatorTerminationReason.ReauthRequired); + + diagnostics.MarkStarted(); + + Assert.True(diagnostics.IsRunning); + Assert.False(diagnostics.IsTerminated); + Assert.Null(diagnostics.TerminationReason); + + Assert.Equal(2, diagnostics.StartCount); + Assert.Equal(1, diagnostics.TerminatedCount); + } + + [Fact] + public void Restart_ShouldPreserveRefreshCounters() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkStarted(); + + diagnostics.MarkRefreshAttempt( + UAuthRefreshTrigger.Background); + + diagnostics.MarkRefreshAttempt( + UAuthRefreshTrigger.Proactive); + + diagnostics.MarkStopped(); + diagnostics.MarkStarted(); + + Assert.Equal(2, diagnostics.RefreshAttemptCount); + Assert.Equal(1, diagnostics.BackgroundRefreshCount); + Assert.Equal(1, diagnostics.ProactiveRefreshCount); + } + + // -------------------------------------------------------- + // Refresh trigger counters + // -------------------------------------------------------- + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual, 1, 0, 0, 0, 0, 0)] + [InlineData(UAuthRefreshTrigger.Background, 0, 1, 0, 0, 0, 1)] + [InlineData(UAuthRefreshTrigger.Proactive, 0, 0, 1, 0, 0, 1)] + [InlineData(UAuthRefreshTrigger.Reactive, 0, 0, 0, 1, 0, 1)] + [InlineData(UAuthRefreshTrigger.Recovery, 0, 0, 0, 0, 1, 0)] + public void MarkRefreshAttempt_ShouldIncrementOnlyMatchingCounter( + UAuthRefreshTrigger trigger, + int manual, + int background, + int proactive, + int reactive, + int recovery, + int automatic) + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkRefreshAttempt(trigger); + + Assert.Equal(manual, diagnostics.ManualRefreshCount); + Assert.Equal(background, diagnostics.BackgroundRefreshCount); + Assert.Equal(proactive, diagnostics.ProactiveRefreshCount); + Assert.Equal(reactive, diagnostics.ReactiveRefreshCount); + Assert.Equal(recovery, diagnostics.RecoveryRefreshCount); + Assert.Equal(automatic, diagnostics.AutomaticRefreshCount); Assert.Equal(1, diagnostics.RefreshAttemptCount); - Assert.Equal(1, diagnostics.ManualRefreshCount); + } + + [Fact] + public void AutomaticRefreshCount_ShouldIncludeOnlyAutomaticStrategies() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkRefreshAttempt(UAuthRefreshTrigger.Manual); + diagnostics.MarkRefreshAttempt(UAuthRefreshTrigger.Recovery); + Assert.Equal(0, diagnostics.AutomaticRefreshCount); + Assert.Equal(2, diagnostics.RefreshAttemptCount); + + diagnostics.MarkRefreshAttempt(UAuthRefreshTrigger.Background); + diagnostics.MarkRefreshAttempt(UAuthRefreshTrigger.Proactive); + diagnostics.MarkRefreshAttempt(UAuthRefreshTrigger.Reactive); + + Assert.Equal(3, diagnostics.AutomaticRefreshCount); + Assert.Equal(5, diagnostics.RefreshAttemptCount); } [Fact] - public void MarkAutomaticRefresh_ShouldIncrementAutomaticAndTotalCounters() + public void RefreshAttemptCount_ShouldIncludeAllTriggers() { var diagnostics = new UAuthClientDiagnostics(); - diagnostics.MarkAutomaticRefresh(); - Assert.Equal(1, diagnostics.RefreshAttemptCount); - Assert.Equal(1, diagnostics.AutomaticRefreshCount); - Assert.Equal(0, diagnostics.ManualRefreshCount); + foreach (var trigger in Enum.GetValues()) + { + diagnostics.MarkRefreshAttempt(trigger); + diagnostics.MarkRefreshAttempt(trigger); + } + + Assert.Equal(2, diagnostics.ManualRefreshCount); + Assert.Equal(2, diagnostics.BackgroundRefreshCount); + Assert.Equal(2, diagnostics.ProactiveRefreshCount); + Assert.Equal(2, diagnostics.ReactiveRefreshCount); + Assert.Equal(2, diagnostics.RecoveryRefreshCount); + + Assert.Equal(6, diagnostics.AutomaticRefreshCount); + Assert.Equal(10, diagnostics.RefreshAttemptCount); } + [Fact] + public void MarkRefreshAttempt_InvalidTrigger_ShouldThrow() + { + var diagnostics = new UAuthClientDiagnostics(); + + Assert.Throws(() => + diagnostics.MarkRefreshAttempt( + (UAuthRefreshTrigger)999)); + + Assert.Equal(0, diagnostics.RefreshAttemptCount); + Assert.Equal(0, diagnostics.AutomaticRefreshCount); + } + + [Fact] + public void MarkRefreshAttempt_ShouldBeThreadSafe() + { + var diagnostics = new UAuthClientDiagnostics(); + + const int attemptsPerTrigger = 1000; + + var triggers = Enum.GetValues(); + + Parallel.For( + 0, + attemptsPerTrigger * triggers.Length, + i => + { + var trigger = triggers[i % triggers.Length]; + + diagnostics.MarkRefreshAttempt(trigger); + }); + + Assert.Equal( + attemptsPerTrigger, + diagnostics.ManualRefreshCount); + + Assert.Equal( + attemptsPerTrigger, + diagnostics.BackgroundRefreshCount); + + Assert.Equal( + attemptsPerTrigger, + diagnostics.ProactiveRefreshCount); + + Assert.Equal( + attemptsPerTrigger, + diagnostics.ReactiveRefreshCount); + + Assert.Equal( + attemptsPerTrigger, + diagnostics.RecoveryRefreshCount); + + Assert.Equal( + attemptsPerTrigger * 3, + diagnostics.AutomaticRefreshCount); + + Assert.Equal( + attemptsPerTrigger * 5, + diagnostics.RefreshAttemptCount); + } + + // -------------------------------------------------------- + // Refresh outcomes + // -------------------------------------------------------- + [Fact] public void MarkRefreshOutcomes_ShouldIncrementCorrectCounters() { var diagnostics = new UAuthClientDiagnostics(); + diagnostics.MarkRefreshTouched(); + diagnostics.MarkRefreshRotated(); diagnostics.MarkRefreshNoOp(); diagnostics.MarkRefreshReauthRequired(); diagnostics.MarkRefreshSuccess(); Assert.Equal(1, diagnostics.RefreshTouchedCount); + Assert.Equal(1, diagnostics.RefreshRotatedCount); Assert.Equal(1, diagnostics.RefreshNoOpCount); Assert.Equal(1, diagnostics.RefreshReauthRequiredCount); Assert.Equal(1, diagnostics.RefreshSuccessCount); } [Fact] - public void MarkTerminated_ShouldSetTerminationState_AndIncrementCounter() + public void MarkRefreshOutcome_ShouldNotIncrementAttemptCounters() { var diagnostics = new UAuthClientDiagnostics(); - diagnostics.MarkTerminated(CoordinatorTerminationReason.ReauthRequired); - Assert.True(diagnostics.IsTerminated); - Assert.Equal(CoordinatorTerminationReason.ReauthRequired, diagnostics.TerminationReason); - Assert.Equal(1, diagnostics.TerminatedCount); + diagnostics.MarkRefreshTouched(); + diagnostics.MarkRefreshRotated(); + diagnostics.MarkRefreshNoOp(); + diagnostics.MarkRefreshReauthRequired(); + diagnostics.MarkRefreshSuccess(); + + Assert.Equal(0, diagnostics.RefreshAttemptCount); + Assert.Equal(0, diagnostics.AutomaticRefreshCount); + Assert.Equal(0, diagnostics.ManualRefreshCount); + } + + [Fact] + public void MarkRefreshAttempt_ShouldNotIncrementOutcomeCounters() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkRefreshAttempt( + UAuthRefreshTrigger.Proactive); + + Assert.Equal(1, diagnostics.RefreshAttemptCount); + + Assert.Equal(0, diagnostics.RefreshTouchedCount); + Assert.Equal(0, diagnostics.RefreshRotatedCount); + Assert.Equal(0, diagnostics.RefreshNoOpCount); + Assert.Equal(0, diagnostics.RefreshReauthRequiredCount); + Assert.Equal(0, diagnostics.RefreshSuccessCount); + } + + [Fact] + public void MarkRefreshReauthRequired_ShouldNotTerminateBackgroundCoordinator() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.MarkStarted(); + diagnostics.MarkRefreshReauthRequired(); + + Assert.Equal(1, diagnostics.RefreshReauthRequiredCount); + + Assert.True(diagnostics.IsRunning); + Assert.False(diagnostics.IsTerminated); + Assert.Equal(0, diagnostics.TerminatedCount); + } + + // -------------------------------------------------------- + // Changed event + // -------------------------------------------------------- + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual)] + [InlineData(UAuthRefreshTrigger.Background)] + [InlineData(UAuthRefreshTrigger.Proactive)] + [InlineData(UAuthRefreshTrigger.Reactive)] + [InlineData(UAuthRefreshTrigger.Recovery)] + public void MarkRefreshAttempt_ShouldRaiseChangedOnce( + UAuthRefreshTrigger trigger) + { + var diagnostics = new UAuthClientDiagnostics(); + + var changeCount = 0; + + diagnostics.Changed += () => changeCount++; + + diagnostics.MarkRefreshAttempt(trigger); + + Assert.Equal(1, changeCount); } [Fact] - public void ChangedEvent_ShouldFire_OnStateChanges() + public void ChangedEvent_ShouldFire_OnLifecycleAndOutcomeChanges() { var diagnostics = new UAuthClientDiagnostics(); + var changeCount = 0; diagnostics.Changed += () => changeCount++; @@ -87,33 +434,69 @@ public void ChangedEvent_ShouldFire_OnStateChanges() diagnostics.MarkStarted(); Assert.Equal(1, changeCount); - diagnostics.MarkManualRefresh(); + diagnostics.MarkRefreshTouched(); Assert.Equal(2, changeCount); - diagnostics.MarkRefreshTouched(); + diagnostics.MarkRefreshRotated(); Assert.Equal(3, changeCount); + diagnostics.MarkRefreshNoOp(); + Assert.Equal(4, changeCount); + + diagnostics.MarkRefreshSuccess(); + Assert.Equal(5, changeCount); + + diagnostics.MarkRefreshReauthRequired(); + Assert.Equal(6, changeCount); + diagnostics.MarkTerminated( CoordinatorTerminationReason.ReauthRequired); - Assert.Equal(4, changeCount); + Assert.Equal(7, changeCount); + + diagnostics.MarkStopped(); + Assert.Equal(8, changeCount); } [Fact] - public void MarkTerminated_ShouldBeIdempotent_ForStateButCountShouldIncrease() + public void InvalidRefreshTrigger_ShouldNotRaiseChanged() { var diagnostics = new UAuthClientDiagnostics(); - diagnostics.MarkTerminated(CoordinatorTerminationReason.ReauthRequired); - diagnostics.MarkTerminated(CoordinatorTerminationReason.ReauthRequired); - Assert.True(diagnostics.IsTerminated); - Assert.Equal(2, diagnostics.TerminatedCount); + var changeCount = 0; + + diagnostics.Changed += () => changeCount++; + + Assert.Throws(() => + diagnostics.MarkRefreshAttempt( + (UAuthRefreshTrigger)999)); + + Assert.Equal(0, changeCount); + } + + // -------------------------------------------------------- + // Background scheduling + // -------------------------------------------------------- + + [Fact] + public void SetNextAutomaticRefresh_ShouldStoreScheduledTime() + { + var diagnostics = new UAuthClientDiagnostics(); + + var scheduledAt = DateTimeOffset.UtcNow.AddMinutes(5); + + diagnostics.SetNextAutomaticRefresh(scheduledAt); + + Assert.Equal( + scheduledAt, + diagnostics.NextAutomaticRefreshAt); } [Fact] public void SetNextAutomaticRefresh_ShouldNotifyOnlyWhenChanged() { var diagnostics = new UAuthClientDiagnostics(); + var changeCount = 0; diagnostics.Changed += () => changeCount++; @@ -126,10 +509,536 @@ public void SetNextAutomaticRefresh_ShouldNotifyOnlyWhenChanged() diagnostics.SetNextAutomaticRefresh(scheduledAt); Assert.Equal(1, changeCount); - diagnostics.SetNextAutomaticRefresh(null); + diagnostics.SetNextAutomaticRefresh( + scheduledAt.AddMinutes(1)); + Assert.Equal(2, changeCount); diagnostics.SetNextAutomaticRefresh(null); - Assert.Equal(2, changeCount); + Assert.Equal(3, changeCount); + + diagnostics.SetNextAutomaticRefresh(null); + Assert.Equal(3, changeCount); + } + + [Fact] + public void SetNextAutomaticRefresh_ShouldNotIncrementAttempts() + { + var diagnostics = new UAuthClientDiagnostics(); + + diagnostics.SetNextAutomaticRefresh( + DateTimeOffset.UtcNow.AddMinutes(5)); + + Assert.Equal(0, diagnostics.RefreshAttemptCount); + Assert.Equal(0, diagnostics.BackgroundRefreshCount); + } + + // -------------------------------------------------------- + // Refresh eligibility + // -------------------------------------------------------- + + [Fact] + public void AnonymousClient_ShouldNotHaveRefreshEligibility() + { + var fixture = new DiagnosticsFixture(); + + Assert.Null(fixture.Diagnostics.NextRefreshEligibleAt); + Assert.Null(fixture.Diagnostics.NextAutomaticRefreshAt); + } + + [Fact] + public void CookieAuthentication_ShouldExposeIntervalBasedEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(5), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void OpaqueAuthentication_ShouldExposeIntervalBasedEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "opaque-token", + TimeSpan.FromHours(1), + TokenFormat.Opaque); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(5), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void JwtAuthentication_ShouldExposeExpirationBasedEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "jwt-token", + TimeSpan.FromMinutes(10)); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(9), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void ProactiveOnly_ShouldExposeEligibilityWithoutBackgroundSchedule() + { + var fixture = new DiagnosticsFixture( + background: false); + + fixture.AuthenticateCookie(); + + Assert.NotNull( + fixture.Diagnostics.NextRefreshEligibleAt); + + Assert.Null( + fixture.Diagnostics.NextAutomaticRefreshAt); + + Assert.False(fixture.Diagnostics.IsRunning); + + Assert.Equal( + 0, + fixture.Diagnostics.BackgroundRefreshCount); + } + + [Fact] + public void Eligibility_ShouldRemainDueUntilRefreshed() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + var original = + fixture.Diagnostics.NextRefreshEligibleAt; + + fixture.Clock.Advance(TimeSpan.FromMinutes(10)); + + Assert.Equal( + original, + fixture.Diagnostics.NextRefreshEligibleAt); + + Assert.True( + fixture.Schedule.IsDue(fixture.Store.Capture())); + + Assert.Equal( + 0, + fixture.Diagnostics.RefreshAttemptCount); + } + + [Fact] + public void SuccessfulCookieRefresh_ShouldUpdateEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + fixture.Clock.Advance(TimeSpan.FromMinutes(5)); + + fixture.Schedule.MarkRefreshed( + fixture.Store.Capture()); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(5), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void JwtRotation_ShouldUpdateEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "original-token", + TimeSpan.FromMinutes(10)); + + fixture.Clock.Advance(TimeSpan.FromMinutes(9)); + + var expected = fixture.Store.Capture(); + + Assert.True( + fixture.Store.TryRotate( + expected, + fixture.CreateToken( + "rotated-token", + TimeSpan.FromMinutes(10)))); + + fixture.Schedule.MarkRefreshed(expected); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(9), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void BackgroundSchedule_ShouldBeIndependentOfEligibility() + { + var fixture = new DiagnosticsFixture( + background: true); + + fixture.AuthenticateCookie(); + + var eligibility = + fixture.Diagnostics.NextRefreshEligibleAt; + + var scheduledAt = + fixture.Clock.UtcNow.AddMinutes(7); + + fixture.Diagnostics.SetNextAutomaticRefresh( + scheduledAt); + + Assert.Equal( + eligibility, + fixture.Diagnostics.NextRefreshEligibleAt); + + Assert.Equal( + scheduledAt, + fixture.Diagnostics.NextAutomaticRefreshAt); + + fixture.Diagnostics.SetNextAutomaticRefresh(null); + + Assert.Null( + fixture.Diagnostics.NextAutomaticRefreshAt); + + Assert.Equal( + eligibility, + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void StoppingBackground_ShouldNotClearProactiveEligibility() + { + var fixture = new DiagnosticsFixture( + background: true); + + fixture.AuthenticateCookie(); + + fixture.Diagnostics.MarkStarted(); + + fixture.Diagnostics.SetNextAutomaticRefresh( + fixture.Clock.UtcNow.AddMinutes(5)); + + var eligibility = + fixture.Diagnostics.NextRefreshEligibleAt; + + fixture.Diagnostics.MarkStopped(); + + Assert.Null( + fixture.Diagnostics.NextAutomaticRefreshAt); + + Assert.Equal( + eligibility, + fixture.Diagnostics.NextRefreshEligibleAt); + } + + // -------------------------------------------------------- + // Read-only diagnostics + // -------------------------------------------------------- + + [Fact] + public void ReadingEligibility_ShouldNotPostponeSchedule() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "jwt-token", + TimeSpan.FromMinutes(10)); + + var original = + fixture.Diagnostics.NextRefreshEligibleAt; + + for (var i = 0; i < 5; i++) + { + fixture.Clock.Advance( + TimeSpan.FromMinutes(1)); + + Assert.Equal( + original, + fixture.Diagnostics.NextRefreshEligibleAt); + } + + Assert.Equal( + 0, + fixture.Diagnostics.RefreshAttemptCount); + } + + [Fact] + public void ReadingEligibility_ShouldNotInitializeJwtSchedule() + { + var fixture = new DiagnosticsFixture(); + + fixture.Store.Replace( + fixture.CreateToken( + "unscheduled-token", + TimeSpan.FromSeconds(30))); + + // No schedule initialization has occurred yet. + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + + fixture.Clock.Advance(TimeSpan.FromSeconds(10)); + + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + + // Explicit authentication initializes the schedule. + fixture.Schedule.MarkAuthenticated( + fixture.Store.Capture()); + + // Remaining lifetime is 20 seconds. + // The threshold is clamped to half that lifetime. + Assert.Equal( + fixture.Clock.UtcNow.AddSeconds(10), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void ReadingEligibility_ShouldNotRaiseChanged() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + var changeCount = 0; + + fixture.Diagnostics.Changed += () => changeCount++; + + _ = fixture.Diagnostics.NextRefreshEligibleAt; + + fixture.Clock.Advance(TimeSpan.FromMinutes(5)); + + _ = fixture.Diagnostics.NextRefreshEligibleAt; + + Assert.Equal(0, changeCount); + } + + // -------------------------------------------------------- + // Authentication lifecycle isolation + // -------------------------------------------------------- + + [Fact] + public void Logout_ShouldClearCookieEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + Assert.NotNull( + fixture.Diagnostics.NextRefreshEligibleAt); + + var expected = fixture.Store.Capture(); + + fixture.Store.Clear(); + + fixture.Schedule.MarkUnauthenticated( + expected.Epoch); + + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void Logout_ShouldClearJwtEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "jwt-token", + TimeSpan.FromMinutes(10)); + + Assert.NotNull( + fixture.Diagnostics.NextRefreshEligibleAt); + + var expected = fixture.Store.Capture(); + + fixture.Store.Clear(); + + fixture.Schedule.MarkUnauthenticated( + expected.Epoch); + + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void ChangedAuthenticationEpoch_ShouldHideStaleEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + Assert.NotNull( + fixture.Diagnostics.NextRefreshEligibleAt); + + // The token store changes before schedule cleanup. + fixture.Store.Clear(); + + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void AccountSwitch_ShouldNotExposePreviousJwtSchedule() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateToken( + "first-user-token", + TimeSpan.FromMinutes(10)); + + fixture.Clock.Advance(TimeSpan.FromMinutes(2)); + + fixture.Store.Replace( + fixture.CreateToken( + "second-user-token", + TimeSpan.FromMinutes(30))); + + Assert.Null( + fixture.Diagnostics.NextRefreshEligibleAt); + + fixture.Schedule.MarkAuthenticated( + fixture.Store.Capture()); + + Assert.Equal( + fixture.Clock.UtcNow.AddMinutes(29), + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void StaleRefreshCompletion_ShouldNotChangeNewAccountEligibility() + { + var fixture = new DiagnosticsFixture(); + + fixture.AuthenticateCookie(); + + var previous = fixture.Store.Capture(); + + fixture.Clock.Advance(TimeSpan.FromMinutes(2)); + + fixture.AuthenticateCookie(); + + var currentEligibility = + fixture.Diagnostics.NextRefreshEligibleAt; + + fixture.Clock.Advance(TimeSpan.FromMinutes(1)); + + fixture.Schedule.MarkRefreshed(previous); + + Assert.Equal( + currentEligibility, + fixture.Diagnostics.NextRefreshEligibleAt); + } + + [Fact] + public void IndependentDiagnosticsInstances_ShouldNotShareState() + { + var first = new DiagnosticsFixture(); + var second = new DiagnosticsFixture(); + + first.AuthenticateCookie(); + + first.Diagnostics.MarkRefreshAttempt( + UAuthRefreshTrigger.Proactive); + + first.Diagnostics.MarkRefreshTouched(); + + Assert.Equal( + 1, + first.Diagnostics.RefreshAttemptCount); + + Assert.NotNull( + first.Diagnostics.NextRefreshEligibleAt); + + Assert.Equal( + 0, + second.Diagnostics.RefreshAttemptCount); + + Assert.Equal( + 0, + second.Diagnostics.RefreshTouchedCount); + + Assert.Null( + second.Diagnostics.NextRefreshEligibleAt); + } + + // -------------------------------------------------------- + // Fixture + // -------------------------------------------------------- + + private sealed class DiagnosticsFixture + { + public TestClock Clock { get; } = new( + new DateTimeOffset( + 2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); + + public InMemoryUAuthTokenStore Store { get; } = new(); + + public UAuthRefreshSchedule Schedule { get; } + + public UAuthClientDiagnostics Diagnostics { get; } + + public DiagnosticsFixture(bool background = false) + { + var options = Options.Create( + new UAuthClientOptions + { + AutoRefresh = new() + { + Background = background, + Proactive = true, + Reactive = true, + Interval = TimeSpan.FromMinutes(5), + RefreshBeforeExpiration = + TimeSpan.FromMinutes(1) + } + }); + + Schedule = new UAuthRefreshSchedule( + Store, + options, + Clock); + + Diagnostics = new UAuthClientDiagnostics( + Schedule); + } + + public void AuthenticateCookie() + { + Store.Clear(); + + Schedule.MarkAuthenticated( + Store.Capture()); + } + + public void AuthenticateToken( + string value, + TimeSpan lifetime, + TokenFormat format = TokenFormat.Jwt) + { + Store.Replace( + CreateToken(value, lifetime, format)); + + Schedule.MarkAuthenticated( + Store.Capture()); + } + + public AccessToken CreateToken( + string value, + TimeSpan lifetime, + TokenFormat format = TokenFormat.Jwt) + { + return new AccessToken + { + Token = value, + Format = format, + ExpiresAt = Clock.UtcNow + lifetime + }; + } } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientProductInfoTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientProductInfoTests.cs index 5d8eb03e..904c445e 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientProductInfoTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientProductInfoTests.cs @@ -17,7 +17,7 @@ public void ProductInfo_Should_Be_Created_With_Valid_Data() ApplicationProfile = UAuthApplicationProfile.BlazorServer, AutoRefresh = new UAuthClientAutoRefreshOptions { - Enabled = true, + Background = true, Interval = TimeSpan.FromMinutes(5) }, Reauth = new UAuthClientReauthOptions diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientRateLimitingTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientRateLimitingTests.cs index 8efd62b1..cf3dc817 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientRateLimitingTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/ClientRateLimitingTests.cs @@ -3,7 +3,6 @@ using CodeBeam.UltimateAuth.Client.Authentication; using CodeBeam.UltimateAuth.Client.Blazor; using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; @@ -16,6 +15,7 @@ using CodeBeam.UltimateAuth.Core.MultiTenancy; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using System.Net; @@ -206,21 +206,74 @@ public async Task LogoutThrottleIsNotSuccessAndDoesNotPublishLogout() [Fact] public async Task AuthorizationAndRecoveryThrottleAreResults_NotForbiddenOrRetry() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync(new UAuthTransportResult { Status = 429, RetryAfter = "30" }); - var result = await CreateClient().Authorization.CheckAsync(new CodeBeam.UltimateAuth.Authorization.Contracts.AuthorizationCheckRequest { Action = "read", Resource = "example" }); + Request.Setup(x => x.SendJsonAsync( + It.IsAny(), + It.IsAny(), + UAuthRequestAuthentication.Recoverable, + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Status = 429, + RetryAfter = "30" + }); + + Request.Setup(x => x.SendJsonAsync( + It.IsAny(), + It.IsAny(), + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Status = 429, + RetryAfter = "30" + }); + + var client = CreateClient(); + + var result = await client.Authorization.CheckAsync( + new CodeBeam.UltimateAuth.Authorization.Contracts.AuthorizationCheckRequest + { + Action = "read", + Resource = "example" + }); + Assert.Equal(429, result.Status); Assert.True(result.Http.IsTooManyRequests); Assert.False(result.Http.IsForbidden); Assert.Equal("rate_limited", result.Problem!.Detail); Assert.Equal(TimeSpan.FromSeconds(30), result.Problem.RetryAfter); Assert.Null(result.Value); - var recovery = await CreateClient().Credentials.CompleteResetAsync(new CodeBeam.UltimateAuth.Credentials.Contracts.CompleteResetCredentialRequest - { Identifier = "user", CredentialType = CredentialType.Password, ResetToken = "proof", NewSecret = "changed-password" }); + + var recovery = await client.Credentials.CompleteResetAsync( + new CodeBeam.UltimateAuth.Credentials.Contracts.CompleteResetCredentialRequest + { + Identifier = "user", + CredentialType = CredentialType.Password, + ResetToken = "proof", + NewSecret = "changed-password" + }); + Assert.Equal(429, recovery.Status); + Assert.True(recovery.Http.IsTooManyRequests); + Assert.False(recovery.Http.IsForbidden); Assert.Equal("rate_limited", recovery.Problem!.Detail); - Events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); - Request.Verify(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + Assert.Equal(TimeSpan.FromSeconds(30), recovery.Problem.RetryAfter); + + Events.Verify(x => x.PublishAsync( + It.IsAny()), + Times.Never); + + Request.Verify(x => x.SendJsonAsync( + It.IsAny(), + It.IsAny(), + UAuthRequestAuthentication.Recoverable, + It.IsAny()), + Times.Once); + + Request.Verify(x => x.SendJsonAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Once); } [Theory] @@ -228,32 +281,120 @@ public async Task AuthorizationAndRecoveryThrottleAreResults_NotForbiddenOrRetry [InlineData(120)] public async Task AutomaticRefreshDefersThrottle_ThenHonorsReal401(int? seconds) { + var ct = TestContext.Current.CancellationToken; var clock = new TestClock(); - var flows = new Mock(); - flows.SetupSequence(x => x.RefreshAsync(true)) - .ReturnsAsync(new RefreshResult { Status = 429, ErrorCode = "rate_limited", RetryAfter = seconds is null ? null : TimeSpan.FromSeconds(seconds.Value) }) - .ReturnsAsync(new RefreshResult { Status = 401, Outcome = RefreshOutcome.ReauthRequired }); + var store = new InMemoryUAuthTokenStore(); + var refresh = new Mock(); var diagnostics = new UAuthClientDiagnostics(); - await using var coordinator = new SessionCoordinator(CreateClient(flows: flows.Object), Mock.Of(), - Options.Create(new UAuthClientOptions { Reauth = new() { Behavior = ReauthBehavior.RaiseEvent } }), diagnostics, clock); - await coordinator.TickAsync(); - await coordinator.TickAsync(); + + var options = Options.Create(new UAuthClientOptions + { + AutoRefresh = new() + { + Background = true, + Interval = TimeSpan.FromMinutes(5) + }, + Reauth = new() + { + Behavior = ReauthBehavior.RaiseEvent + } + }); + + var schedule = new UAuthRefreshSchedule( + store, options, clock); + + // Establish cookie-based authentication. + schedule.MarkAuthenticated(); + + // Make the first background refresh eligible. + clock.Advance(TimeSpan.FromMinutes(5)); + + refresh.SetupSequence(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + It.IsAny(), + It.IsAny())) + .ReturnsAsync(new RefreshResult + { + Status = 429, + ErrorCode = "rate_limited", + RetryAfter = seconds is null + ? null + : TimeSpan.FromSeconds(seconds.Value) + }) + .ReturnsAsync(() => + { + store.Clear(); + + return new RefreshResult + { + Status = 401, + Outcome = RefreshOutcome.ReauthRequired + }; + }); + + await using var coordinator = new SessionCoordinator( + Mock.Of(), + Mock.Of(), + options, + diagnostics, + schedule, + refresh.Object, + clock, + store, + NullLogger.Instance); + + await coordinator.TickAsync(ct); + await coordinator.TickAsync(ct); + Assert.False(diagnostics.IsTerminated); - flows.Verify(x => x.RefreshAsync(true), Times.Once); + + refresh.Verify(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + It.IsAny(), + It.IsAny()), + Times.Once); + clock.Advance(TimeSpan.FromMinutes(3)); - await coordinator.TickAsync(); + + await coordinator.TickAsync(ct); + Assert.True(diagnostics.IsTerminated); - flows.Verify(x => x.RefreshAsync(true), Times.Exactly(2)); + + refresh.Verify(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + It.IsAny(), + It.IsAny()), + Times.Exactly(2)); } + private static UAuthStateManager NewManager(IUAuthClient client, IUAuthClientEvents events, IClock clock) { + var store = new InMemoryUAuthTokenStore(); + + var options = Options.Create(new UAuthClientOptions()); + + var schedule = new UAuthRefreshSchedule(store, options, clock); + + var refresh = new Mock(); + var request = new Mock(); + + request.Setup(x => x.GetLoginTransportAsync( + It.IsAny(), + It.IsAny())) + .ReturnsAsync(new UAuthLoginTransportInfo + { + Supported = false + }); + return new UAuthStateManager( client, events, clock, - new Mock().Object, - new Mock().Object, - Options.Create(new UAuthClientOptions())); + store, + request.Object, + schedule, + refresh.Object, + options); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/SessionCoordinatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/SessionCoordinatorTests.cs index d4924138..397e9c26 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/SessionCoordinatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/SessionCoordinatorTests.cs @@ -1,11 +1,15 @@ -using CodeBeam.UltimateAuth.Client; +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Diagnostics; +using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; @@ -17,59 +21,1546 @@ public class SessionCoordinatorTests public async Task StartAsync_should_not_start_when_auto_refresh_disabled() { var clock = new TestClock(); - var client = new Mock(); - var nav = new Mock(); + var store = new InMemoryUAuthTokenStore(); + var refresh = new Mock(); var diagnostics = new UAuthClientDiagnostics(); var options = Options.Create(new UAuthClientOptions { AutoRefresh = new UAuthClientAutoRefreshOptions { - Enabled = false + Background = false } }); - var coordinator = new SessionCoordinator(client.Object, nav.Object, options, diagnostics, clock); - await coordinator.StartAsync(cancellationToken: TestContext.Current.CancellationToken); + await using var coordinator = CreateCoordinator( + clock, store, refresh.Object, diagnostics, options); + + await coordinator.StartAsync( + ct: TestContext.Current.CancellationToken); Assert.False(diagnostics.IsRunning); + + refresh.Verify(x => x.RefreshIfCurrentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + } + + [Fact] + public async Task Background_Refresh_Should_Preserve_Authentication_Epoch() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult(expected, () => + { + f.Store.TryRotate( + expected, + f.Token("rotated-token")) + .Should().BeTrue(); + + f.Schedule.MarkRefreshed(expected); + + return CoordinatorFixture.Success(); + }); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + var current = f.Store.Capture(); + + current.Epoch.Should().Be(expected.Epoch); + + current.Generation.Should().Be( + expected.Generation + 1); + + current.Token!.Token.Should().Be("rotated-token"); + + f.Schedule.IsDue(current).Should().BeFalse(); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + reauthEvents.Should().Be(0); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Background_Refresh_Should_Support_Cookie_Only_Authentication() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateCookie(); + + f.Clock.Advance(TimeSpan.FromMinutes(5)); + + f.Schedule.IsDue(expected).Should().BeTrue(); + + f.SetupResult(expected, () => + { + f.Schedule.MarkRefreshed(expected); + + return new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Touched + }; + }); + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.Store.Capture().Should().Be(expected); + + f.Schedule.IsAuthenticated(expected) + .Should().BeTrue(); + + f.Schedule.IsDue(expected).Should().BeFalse(); + + f.Schedule.GetNextRefreshAt(expected) + .Should().Be(f.Clock.UtcNow.AddMinutes(5)); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + f.VerifyRefresh(Times.Once()); + } + + [Theory] + [InlineData(400)] + [InlineData(403)] + [InlineData(409)] + [InlineData(503)] + public async Task Background_Failure_Should_Not_Terminate_Coordinator(int status) + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult(expected, () => new RefreshResult + { + IsSuccess = false, + Status = status, + Outcome = RefreshOutcome.None + }); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.Store.Capture().Should().Be(expected); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + reauthEvents.Should().Be(0); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Authoritative_Reauth_Should_Terminate_Coordinator_And_Raise_Event() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult(expected, () => + { + f.Store.TryClear(expected) + .Should().BeTrue(); + + f.Schedule.MarkUnauthenticated( + expected.Epoch); + + return CoordinatorFixture.Reauth(); + }); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + var current = f.Store.Capture(); + + current.Token.Should().BeNull(); + + current.Epoch.Should().Be(expected.Epoch + 1); + + f.Diagnostics.IsTerminated.Should().BeTrue(); + + reauthEvents.Should().Be(1); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task NonAuthoritative_Reauth_Should_Not_Terminate_Coordinator() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + CoordinatorFixture.Reauth); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.Store.Capture().Should().Be(expected); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + reauthEvents.Should().Be(0); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Stale_Reauth_Result_Should_Not_Terminate_New_Authentication() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(pending.Task); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + var tick = f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + tick.IsCompleted.Should().BeFalse(); + + f.Store.TryClear(expected).Should().BeTrue(); + + f.Schedule.MarkUnauthenticated(expected.Epoch); + + f.Store.Replace(f.Token("another-user-token")); + + var current = f.Store.Capture(); + + f.Schedule.MarkAuthenticated(current); + + pending.SetResult(CoordinatorFixture.Reauth()); + + await tick; + + f.Store.Capture().Should().Be(current); + + f.Schedule.IsAuthenticated(current) + .Should().BeTrue(); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + reauthEvents.Should().Be(0); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Background_Refresh_Should_Respect_RetryAfter_Boundary() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.Refresh + .SetupSequence(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .ReturnsAsync(CoordinatorFixture.Throttle(30)) + .ReturnsAsync(CoordinatorFixture.Success()); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + f.Clock.Advance( + TimeSpan.FromSeconds(30) - + TimeSpan.FromTicks(1)); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + f.Clock.Advance(TimeSpan.FromTicks(1)); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Exactly(2)); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + } + + [Fact] + public async Task Stale_Rate_Limit_Result_Should_Not_Throttle_New_Authentication() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(pending.Task); + + var ct = TestContext.Current.CancellationToken; + + var tick = f.Sut.TickAsync(ct); + + f.Store.Replace(f.Token( + "another-user-token", + TimeSpan.FromSeconds(30))); + + var current = f.Store.Capture(); + + f.Schedule.MarkAuthenticated(current); + + f.SetupResult( + current, + CoordinatorFixture.Success); + + pending.SetResult( + CoordinatorFixture.Throttle(120)); + + await tick; + + f.Clock.Advance(TimeSpan.FromSeconds(15)); + + f.Schedule.IsDue(current).Should().BeTrue(); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Exactly(2)); + + f.Store.Capture().Should().Be(current); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + } + + [Fact] + public async Task Start_When_Background_Disabled_Should_Not_Execute_Refresh() + { + await using var f = new CoordinatorFixture(); + + f.Options.AutoRefresh.Background = false; + + f.AuthenticateDue(); + + await f.Sut.StartAsync(TestContext.Current.CancellationToken); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Repeated_Start_Should_Not_Create_Multiple_Background_Loops() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(true); + + return pending.Task.WaitAsync(ct); + }); + + var cancellationToken = + TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(cancellationToken); + + await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + cancellationToken); + + for (var i = 0; i < 10; i++) + { + await f.Sut.StartAsync(cancellationToken); + } + + f.VerifyRefresh(Times.Once()); + + await f.Sut.StopAsync(); + + pending.TrySetResult( + CoordinatorFixture.Success()); + } + + [Fact] + public async Task Stop_Should_Cancel_Background_Refresh_Waiter() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(ct); + + return pending.Task.WaitAsync(ct); + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var backgroundToken = await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + backgroundToken.IsCancellationRequested + .Should().BeFalse(); + + await f.Sut.StopAsync(); + + backgroundToken.IsCancellationRequested + .Should().BeTrue(); + + // Repeated stop must be safe. + await f.Sut.StopAsync(); + + f.VerifyRefresh(Times.Once()); + + pending.TrySetResult( + CoordinatorFixture.Success()); + } + + [Fact] + public async Task Coordinator_Should_Be_Restartable_After_Stop() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var firstEntered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var secondEntered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var calls = 0; + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + if (Interlocked.Increment(ref calls) == 1) + { + firstEntered.TrySetResult(ct); + } + else + { + secondEntered.TrySetResult(ct); + } + + return pending.Task.WaitAsync(ct); + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var firstToken = await firstEntered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + await f.Sut.StopAsync(); + + firstToken.IsCancellationRequested + .Should().BeTrue(); + + await f.Sut.StartAsync(ct); + + var secondToken = await secondEntered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + secondToken.IsCancellationRequested + .Should().BeFalse(); + + secondToken.Should().NotBe(firstToken); + + f.VerifyRefresh(Times.Exactly(2)); + + await f.Sut.StopAsync(); + + secondToken.IsCancellationRequested + .Should().BeTrue(); + + pending.TrySetResult( + CoordinatorFixture.Success()); + } + + [Fact] + public async Task Start_Should_Honor_PreCancelled_Token() + { + await using var f = new CoordinatorFixture(); + + f.AuthenticateDue(); + + using var cts = new CancellationTokenSource(); + + cts.Cancel(); + + Func act = () => + f.Sut.StartAsync(cts.Token); + + await act.Should() + .ThrowAsync(); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Tick_Should_Honor_PreCancelled_Token() + { + await using var f = new CoordinatorFixture(); + + f.AuthenticateDue(); + + using var cts = new CancellationTokenSource(); + + cts.Cancel(); + + Func act = () => + f.Sut.TickAsync(cts.Token); + + await act.Should() + .ThrowAsync(); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Dispose_Should_Cancel_Active_Background_Waiter() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(ct); + + return pending.Task.WaitAsync(ct); + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var backgroundToken = await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + + await f.Sut.DisposeAsync(); + + backgroundToken.IsCancellationRequested.Should().BeTrue(); + + pending.TrySetResult(CoordinatorFixture.Success()); + } + + [Fact] + public async Task Background_Throttle_Should_Not_Carry_Over_To_New_Authentication() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + () => CoordinatorFixture.Throttle(120)); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + // A different authentication lifecycle starts + // while the previous one is throttled. + f.Store.Replace(f.Token( + "another-user-token", + TimeSpan.FromSeconds(30))); + + var current = f.Store.Capture(); + + f.Schedule.MarkAuthenticated(current); + + f.Clock.Advance(TimeSpan.FromSeconds(15)); + + f.Schedule.IsDue(current).Should().BeTrue(); + + f.SetupResult( + current, + CoordinatorFixture.Success); + + await f.Sut.TickAsync(ct); + + f.Refresh.Verify(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + current, + It.IsAny()), + Times.Once); + + f.VerifyRefresh(Times.Exactly(2)); + } + + [Fact] + public async Task Tick_Should_Not_Request_Refresh_Before_Schedule_Is_Due() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateJwt(); + + f.Schedule.IsDue(expected).Should().BeFalse(); + + f.SetupResult( + expected, + CoordinatorFixture.Success); + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Anonymous_Tick_Should_Not_Request_Refresh() + { + await using var f = new CoordinatorFixture(); + + var expected = f.Store.Capture(); + + f.Schedule.IsAuthenticated(expected) + .Should().BeFalse(); + + f.Schedule.IsDue(expected).Should().BeFalse(); + + f.SetupResult( + expected, + CoordinatorFixture.Success); + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Tick_Should_Not_Refresh_When_Background_Disabled() + { + await using var f = new CoordinatorFixture(); + + f.Options.AutoRefresh.Background = false; + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + CoordinatorFixture.Success); + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Background_Throttle_Should_Survive_Token_Rotation_In_Same_Epoch() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + () => CoordinatorFixture.Throttle(120)); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + f.Store.TryRotate( + expected, + f.Token( + "rotated-token", + TimeSpan.FromSeconds(30))) + .Should().BeTrue(); + + f.Schedule.MarkRefreshed(expected); + + var current = f.Store.Capture(); + + current.Epoch.Should().Be(expected.Epoch); + + f.Clock.Advance(TimeSpan.FromSeconds(15)); + + f.Schedule.IsDue(current).Should().BeTrue(); + + f.SetupResult( + current, + CoordinatorFixture.Success); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + f.Clock.Advance(TimeSpan.FromSeconds(105)); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Exactly(2)); + } + + [Fact] + public async Task New_Cookie_Authentication_Should_Not_Inherit_Previous_Throttle() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + () => CoordinatorFixture.Throttle(600)); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Once()); + + f.Store.Clear(); + + f.Schedule.MarkUnauthenticated(expected.Epoch); + + var current = f.AuthenticateCookie(); + + f.Clock.Advance(TimeSpan.FromMinutes(5)); + + f.Schedule.IsDue(current).Should().BeTrue(); + + f.SetupResult( + current, + CoordinatorFixture.Success); + + await f.Sut.TickAsync(ct); + + f.VerifyRefresh(Times.Exactly(2)); + + f.Schedule.IsAuthenticated(current) + .Should().BeTrue(); } [Fact] - public async Task ReauthRequired_should_raise_event() + public async Task Concurrent_Starts_Should_Create_Only_One_Background_Loop() { - var clock = new TestClock(); + await using var f = new CoordinatorFixture(); - var client = new Mock(); - var nav = new Mock(); - var diagnostics = new UAuthClientDiagnostics(); + var expected = f.AuthenticateDue(); - client.Setup(x => x.Flows.RefreshAsync(true)) - .ReturnsAsync(new RefreshResult - { - Outcome = RefreshOutcome.ReauthRequired - }); + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); - var options = Options.Create(new UAuthClientOptions + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var startGate = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(true); + + return pending.Task.WaitAsync(ct); + }); + + var ct = TestContext.Current.CancellationToken; + + var starts = Enumerable.Range(0, 32) + .Select(_ => Task.Run(async () => + { + await startGate.Task.WaitAsync(ct); + + await f.Sut.StartAsync(ct); + }, ct)) + .ToArray(); + + try { - AutoRefresh = new UAuthClientAutoRefreshOptions + startGate.SetResult(true); + + await Task.WhenAll(starts) + .WaitAsync(TimeSpan.FromSeconds(5), ct); + + await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), ct); + + f.VerifyRefresh(Times.Once()); + } + finally + { + pending.TrySetResult( + CoordinatorFixture.Success()); + + await f.Sut.StopAsync(); + } + } + + [Fact] + public async Task Stop_Should_Wait_For_Background_Loop_To_Exit() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(ct); + + // Simulate a waiter that has not yet + // completed its cancellation cleanup. + return pending.Task; + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var backgroundToken = await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), ct); + + var stop = f.Sut.StopAsync(); + + try + { + backgroundToken.IsCancellationRequested + .Should().BeTrue(); + + stop.IsCompleted.Should().BeFalse(); + } + finally + { + pending.TrySetResult( + CoordinatorFixture.Success()); + + await stop.WaitAsync( + TimeSpan.FromSeconds(5), ct); + } + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Concurrent_Stops_Should_Wait_For_Same_Background_Loop() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(ct); + + return pending.Task; + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var backgroundToken = await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), ct); + + var stops = Enumerable.Range(0, 16) + .Select(_ => f.Sut.StopAsync()) + .ToArray(); + + try + { + backgroundToken.IsCancellationRequested + .Should().BeTrue(); + + stops.Should().OnlyContain( + task => !task.IsCompleted); + } + finally + { + pending.TrySetResult( + CoordinatorFixture.Success()); + + await Task.WhenAll(stops) + .WaitAsync(TimeSpan.FromSeconds(5), ct); + } + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Start_During_Stop_Should_Wait_For_Previous_Loop() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var firstEntered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var secondEntered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var firstPending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var secondPending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var calls = 0; + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + if (Interlocked.Increment(ref calls) == 1) + { + firstEntered.TrySetResult(ct); + + return firstPending.Task; + } + + secondEntered.TrySetResult(ct); + + return secondPending.Task.WaitAsync(ct); + }); + + var cancellationToken = + TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(cancellationToken); + + var firstToken = await firstEntered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + cancellationToken); + + var stop = f.Sut.StopAsync(); + + var restart = f.Sut.StartAsync(cancellationToken); + + try + { + firstToken.IsCancellationRequested + .Should().BeTrue(); + + restart.IsCompleted.Should().BeFalse(); + + secondEntered.Task.IsCompleted + .Should().BeFalse(); + + f.VerifyRefresh(Times.Once()); + + firstPending.SetResult( + CoordinatorFixture.Success()); + + await stop.WaitAsync( + TimeSpan.FromSeconds(5), + cancellationToken); + + await restart.WaitAsync( + TimeSpan.FromSeconds(5), + cancellationToken); + + var secondToken = + await secondEntered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + cancellationToken); + + secondToken.IsCancellationRequested + .Should().BeFalse(); + + secondToken.Should().NotBe(firstToken); + + f.VerifyRefresh(Times.Exactly(2)); + } + finally + { + firstPending.TrySetResult( + CoordinatorFixture.Success()); + + secondPending.TrySetResult( + CoordinatorFixture.Success()); + + await f.Sut.StopAsync(); + } + } + + [Fact] + public async Task Start_After_Dispose_Should_Throw() + { + await using var f = new CoordinatorFixture(); + + f.AuthenticateDue(); + + await f.Sut.DisposeAsync(); + + Func act = () => f.Sut.StartAsync( + TestContext.Current.CancellationToken); + + await act.Should() + .ThrowAsync(); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Tick_After_Dispose_Should_Throw() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + f.SetupResult( + expected, + CoordinatorFixture.Success); + + await f.Sut.DisposeAsync(); + + Func act = () => f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + await act.Should() + .ThrowAsync(); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Repeated_Dispose_Should_Be_Safe() + { + await using var f = new CoordinatorFixture(); + + await f.Sut.DisposeAsync(); + + await f.Sut.DisposeAsync(); + + await f.Sut.DisposeAsync(); + + await f.Sut.StopAsync(); + + f.VerifyRefresh(Times.Never()); + } + + [Fact] + public async Task Dispose_Should_Wait_For_Background_Loop_To_Exit() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot __, + CancellationToken ct) => + { + entered.TrySetResult(ct); + + return pending.Task; + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + var backgroundToken = await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), ct); + + var dispose = f.Sut.DisposeAsync().AsTask(); + + try + { + backgroundToken.IsCancellationRequested + .Should().BeTrue(); + + dispose.IsCompleted.Should().BeFalse(); + } + finally + { + pending.TrySetResult( + CoordinatorFixture.Success()); + + await dispose.WaitAsync( + TimeSpan.FromSeconds(5), ct); + } + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Cancelled_Background_Waiter_Should_Not_Raise_Reauth_Event() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(pending.Task); + + var reauthEvents = 0; + + f.Sut.ReauthRequired += () => reauthEvents++; + + using var cts = new CancellationTokenSource(); + + var tick = f.Sut.TickAsync(cts.Token); + + tick.IsCompleted.Should().BeFalse(); + + cts.Cancel(); + + f.Store.TryClear(expected) + .Should().BeTrue(); + + f.Schedule.MarkUnauthenticated(expected.Epoch); + + pending.SetResult( + CoordinatorFixture.Reauth()); + + await tick; + + reauthEvents.Should().Be(0); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + + f.Store.Capture().Token.Should().BeNull(); + + f.VerifyRefresh(Times.Once()); + } + + [Fact] + public async Task Cancelled_Background_Waiter_Should_Not_Apply_Throttle() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .SetupSequence(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(pending.Task) + .ReturnsAsync(CoordinatorFixture.Success()); + + using var cts = new CancellationTokenSource(); + + var tick = f.Sut.TickAsync(cts.Token); + + tick.IsCompleted.Should().BeFalse(); + + cts.Cancel(); + + pending.SetResult( + CoordinatorFixture.Throttle(120)); + + await tick; + + await f.Sut.TickAsync( + TestContext.Current.CancellationToken); + + f.VerifyRefresh(Times.Exactly(2)); + + f.Store.Capture().Should().Be(expected); + + f.Diagnostics.IsTerminated.Should().BeFalse(); + } + + [Fact] + public async Task Dispose_During_Pending_Restart_Should_Prevent_New_Loop() + { + await using var f = new CoordinatorFixture(); + + var expected = f.AuthenticateDue(); + + var entered = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + f.Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .Returns(() => { - Enabled = true, - Interval = TimeSpan.FromSeconds(5) - }, - Reauth = new UAuthClientReauthOptions + entered.TrySetResult(true); + + return pending.Task; + }); + + var ct = TestContext.Current.CancellationToken; + + await f.Sut.StartAsync(ct); + + await entered.Task.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + var stop = f.Sut.StopAsync(); + + var restart = f.Sut.StartAsync(ct); + + var dispose = f.Sut.DisposeAsync().AsTask(); + + try + { + stop.IsCompleted.Should().BeFalse(); + + restart.IsCompleted.Should().BeFalse(); + + dispose.IsCompleted.Should().BeFalse(); + } + finally + { + pending.TrySetResult( + CoordinatorFixture.Success()); + + await Task.WhenAll(stop, dispose) + .WaitAsync(TimeSpan.FromSeconds(5), ct); + } + + Func act = () => restart.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + await act.Should() + .ThrowAsync(); + + f.VerifyRefresh(Times.Once()); + } + + + private static SessionCoordinator CreateCoordinator( + TestClock clock, + IUAuthTokenStore store, + IUAuthRefreshCoordinator refresh, + UAuthClientDiagnostics diagnostics, + IOptions options) + { + var schedule = new UAuthRefreshSchedule(store, options, clock); + + return new SessionCoordinator( + Mock.Of(), + Mock.Of(), + options, + diagnostics, + schedule, + refresh, + clock, + store, + NullLogger.Instance); + } + + private sealed class CoordinatorFixture : IAsyncDisposable + { + public TestClock Clock { get; } = new( + new DateTimeOffset( + 2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); + + public InMemoryUAuthTokenStore Store { get; } = new(); + + public Mock Refresh { get; } = new(); + + public UAuthClientDiagnostics Diagnostics { get; } = new(); + + public UAuthClientOptions Options { get; } = new() + { + AutoRefresh = new UAuthClientAutoRefreshOptions { - Behavior = ReauthBehavior.RaiseEvent + Background = true, + Reactive = true, + Proactive = true, + Interval = TimeSpan.FromMinutes(5), + RefreshBeforeExpiration = TimeSpan.FromMinutes(1) } - }); + }; + + public UAuthRefreshSchedule Schedule { get; } + + public SessionCoordinator Sut { get; } + + public CoordinatorFixture() + { + Options.Reauth.Behavior = ReauthBehavior.RaiseEvent; + + var options = Microsoft.Extensions.Options.Options + .Create(Options); - var coordinator = new SessionCoordinator(client.Object, nav.Object, options, diagnostics, clock); - var triggered = false; - coordinator.ReauthRequired += () => triggered = true; + Schedule = new UAuthRefreshSchedule( + Store, + options, + Clock); - await coordinator.TickAsync(); + Sut = new SessionCoordinator( + Mock.Of(), + Mock.Of(), + options, + Diagnostics, + Schedule, + Refresh.Object, + Clock, + Store, + NullLogger.Instance); + } - Assert.True(triggered); - Assert.True(diagnostics.IsTerminated); + public AccessToken Token(string value, TimeSpan? lifetime = null) + { + return new AccessToken + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = Clock.UtcNow + (lifetime ?? TimeSpan.FromMinutes(10)) + }; + } + + public UAuthTokenSnapshot AuthenticateJwt(TimeSpan? lifetime = null) + { + Store.Replace(Token("original-token", lifetime)); + + var snapshot = Store.Capture(); + + Schedule.MarkAuthenticated(snapshot); + + return snapshot; + } + + public UAuthTokenSnapshot AuthenticateCookie() + { + Store.Clear(); + + var snapshot = Store.Capture(); + + Schedule.MarkAuthenticated(snapshot); + + return snapshot; + } + + public UAuthTokenSnapshot AuthenticateDue() + { + var snapshot = AuthenticateJwt(); + + Clock.Advance(TimeSpan.FromMinutes(9)); + + Schedule.IsDue(snapshot).Should().BeTrue(); + + return snapshot; + } + + public void SetupResult(UAuthTokenSnapshot expected, Func result) + { + Refresh + .Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + It.IsAny())) + .ReturnsAsync(result); + } + + public void VerifyRefresh(Times times) + { + Refresh.Verify(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + It.IsAny(), + It.IsAny()), + times); + } + + public static RefreshResult Success() + { + return new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Rotated + }; + } + + public static RefreshResult Reauth() + { + return new RefreshResult + { + IsSuccess = false, + Status = 401, + Outcome = RefreshOutcome.ReauthRequired + }; + } + + public static RefreshResult Throttle(int seconds = 30) + { + return new RefreshResult + { + IsSuccess = false, + Status = 429, + Outcome = RefreshOutcome.None, + ErrorCode = "rate_limited", + RetryAfter = TimeSpan.FromSeconds(seconds) + }; + } + + public ValueTask DisposeAsync() + { + return Sut.DisposeAsync(); + } } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientAuthorizationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientAuthorizationTests.cs index 5efa066d..e0fdf330 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientAuthorizationTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientAuthorizationTests.cs @@ -1,6 +1,5 @@ using CodeBeam.UltimateAuth.Authorization.Contracts; using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Defaults; using CodeBeam.UltimateAuth.Core.Domain; @@ -19,6 +18,7 @@ public async Task AssignRole_Should_Call_Correct_Endpoint_And_Publish_Event() Request.Setup(x => x.SendJsonAsync( It.IsAny(), It.IsAny(), + UAuthRequestAuthentication.Recoverable, It.IsAny())) .ReturnsAsync(Success()); @@ -34,22 +34,20 @@ public async Task AssignRole_Should_Call_Correct_Endpoint_And_Publish_Event() Request.Verify(x => x.SendJsonAsync( $"/auth/admin/authorization/users/{request.UserKey.Value}/roles/assign", - It.Is(r => - r.UserKey == request.UserKey && - r.RoleName == request.RoleName), + It.Is(r => r.UserKey == request.UserKey && r.RoleName == request.RoleName), + UAuthRequestAuthentication.Recoverable, It.IsAny()), Times.Once); Events.Verify(x => x.PublishAsync( - It.Is(e => - e.Type == UAuthStateEvent.AuthorizationChanged)), + It.Is(e => e.Type == UAuthStateEvent.AuthorizationChanged)), Times.Once); } [Fact] public async Task RemoveRole_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateClient(); @@ -67,7 +65,7 @@ public async Task RemoveRole_Should_Publish_Event_On_Success() [Fact] public async Task AssignRole_Should_NOT_Publish_Event_On_Failure() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = false, Status = 400 }); var client = CreateClient(); @@ -86,7 +84,7 @@ public async Task AssignRole_Should_NOT_Publish_Event_On_Failure() [Fact] public async Task Check_Should_Return_Result() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new AuthorizationResult { IsAllowed = true @@ -101,7 +99,7 @@ public async Task Check_Should_Return_Result() [Fact] public async Task QueryRoles_Should_Return_Data() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new PagedResult( new List(), 0, 1, 10, null, false))); @@ -139,12 +137,12 @@ public async Task GetMyRoles_Should_Call_Correct_Endpoint_And_Return_Data() descending: false) }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); var result = await client.Authorization.GetMyRolesAsync(); - Request.Verify(x => x.SendJsonAsync("/auth/me/authorization/roles/get", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/me/authorization/roles/get", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); result.IsSuccess.Should().BeTrue(); result.Value.Should().NotBeNull(); @@ -180,12 +178,12 @@ public async Task GetUserRoles_Should_Call_Admin_Endpoint() descending: false) }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); var result = await client.Authorization.GetUserRolesAsync(userKey); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/authorization/users/{userKey.Value}/roles/get", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/authorization/users/{userKey.Value}/roles/get", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); result.IsSuccess.Should().BeTrue(); result.Value.Should().NotBeNull(); @@ -197,7 +195,7 @@ public async Task GetUserRoles_Should_Call_Admin_Endpoint() [Fact] public async Task CreateRole_Should_Return_Result() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new RoleInfo() { Name = "admin" })); var client = CreateClient(); @@ -209,7 +207,7 @@ public async Task CreateRole_Should_Return_Result() [Fact] public async Task RenameRole_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = true, Status = 200 }); var client = CreateClient(); @@ -226,7 +224,7 @@ public async Task RenameRole_Should_Publish_Event_On_Success() [Fact] public async Task RenameRole_Should_NOT_Publish_Event_On_Failure() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = false, Status = 400 }); var client = CreateClient(); @@ -243,7 +241,7 @@ await client.Authorization.RenameRoleAsync(new RenameRoleRequest [Fact] public async Task SetRolePermissions_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = true, Status = 200 }); var client = CreateClient(); @@ -261,7 +259,7 @@ public async Task SetRolePermissions_Should_Publish_Event_On_Success() [Fact] public async Task DeleteRole_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new RoleDeleteResult())); var client = CreateClient(); @@ -286,7 +284,7 @@ public async Task Check_Should_Return_Structured_Denial(bool requiresReauthentic Request.Setup(x => x.SendJsonAsync( "/auth/me/authorization/check", - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(expected)); var client = CreateClient(); @@ -315,7 +313,7 @@ public async Task Check_Should_Return_Structured_Denial(bool requiresReauthentic It.Is(r => r.Action == request.Action && r.Resource == request.Resource && - r.ResourceId == request.ResourceId)), + r.ResourceId == request.ResourceId), UAuthRequestAuthentication.Recoverable), Times.Once); } @@ -327,13 +325,13 @@ public async Task GetMyPermissions_Should_Call_Self_Endpoint_And_Return_Data() Permissions = [ Permission.From("users.read"), - Permission.From("reports.*") + Permission.From("reports.*") ] }; Request.Setup(x => x.SendJsonAsync( "/auth/me/authorization/permissions/get", - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); @@ -350,7 +348,7 @@ public async Task GetMyPermissions_Should_Call_Self_Endpoint_And_Return_Data() Request.Verify(x => x.SendJsonAsync( "/auth/me/authorization/permissions/get", - It.IsAny()), + It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); Events.Verify(x => x.PublishAsync( @@ -361,7 +359,7 @@ public async Task GetMyPermissions_Should_Call_Self_Endpoint_And_Return_Data() [Fact] public async Task GetMyPermissions_WhenRequestFails_ReturnsFailure() { - Request.Setup(x => x.SendJsonAsync("/auth/me/authorization/permissions/get", It.IsAny())) + Request.Setup(x => x.SendJsonAsync("/auth/me/authorization/permissions/get", It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = false, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientCredentialsTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientCredentialsTests.cs index e35a07a2..51493da0 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientCredentialsTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientCredentialsTests.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Credentials.Contracts; @@ -14,18 +13,18 @@ public class UAuthClientCredentialTests : UAuthClientTestBase [Fact] public async Task AddMy_Should_Call_Correct_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialAddResult())); var client = CreateCredentialClient(); await client.Credentials.AddMyAsync(new AddCredentialRequest() { Secret = "uauth" }); - Request.Verify(x => x.SendJsonAsync("/auth/me/credentials/add", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/me/credentials/add", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] public async Task ChangeMy_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialChangeResult())); var client = CreateCredentialClient(); @@ -36,7 +35,7 @@ public async Task ChangeMy_Should_Publish_Event_On_Success() [Fact] public async Task ChangeMy_Should_NOT_Publish_Event_On_Failure() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = false, Status = 400 }); var client = CreateCredentialClient(); @@ -47,7 +46,7 @@ public async Task ChangeMy_Should_NOT_Publish_Event_On_Failure() [Fact] public async Task RevokeMy_Should_Publish_Event() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = true, Status = 200 }); var client = CreateCredentialClient(); @@ -58,13 +57,13 @@ public async Task RevokeMy_Should_Publish_Event() [Fact] public async Task AddUser_Should_Call_Admin_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialAddResult())); var client = CreateCredentialClient(); var userKey = UserKey.FromString("user-1"); await client.Credentials.AddUserAsync(userKey, new AddCredentialRequest() { Secret = "uauth" }); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/add", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/add", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } @@ -82,7 +81,7 @@ public async Task DeleteUser_Should_Call_Delete_Endpoint() Request .Setup(x => x.SendJsonAsync( $"/auth/admin/users/{userKey.Value}/credentials/delete", - It.IsAny(), + It.IsAny(), UAuthRequestAuthentication.Recoverable, It.IsAny())) .ReturnsAsync(new UAuthTransportResult { @@ -100,9 +99,8 @@ public async Task DeleteUser_Should_Call_Delete_Endpoint() Request.Verify(x => x.SendJsonAsync( $"/auth/admin/users/{userKey.Value}/credentials/delete", - It.Is(r => - r.Id == request.Id && - r.Mode == request.Mode), + It.Is(r => r.Id == request.Id && r.Mode == request.Mode), + UAuthRequestAuthentication.Recoverable, It.IsAny()), Times.Once); } @@ -143,7 +141,7 @@ public async Task CompleteResetMy_Should_NOT_Publish_Event_On_Failure() [Fact] public async Task BeginResetUser_Should_Call_Admin_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialBeginResetResult())); var client = CreateCredentialClient(); @@ -151,13 +149,13 @@ public async Task BeginResetUser_Should_Call_Admin_Endpoint() await client.Credentials.BeginResetUserAsync(userKey, new BeginResetCredentialRequest() { Identifier = "user1" }); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/reset/begin", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/reset/begin", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] public async Task CompleteResetUser_Should_NOT_Publish_Event() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialActionResult())); var client = CreateCredentialClient(); @@ -169,7 +167,7 @@ public async Task CompleteResetUser_Should_NOT_Publish_Event() [Fact] public async Task ChangeUser_Should_Call_Admin_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new CredentialChangeResult())); var client = CreateCredentialClient(); @@ -177,18 +175,18 @@ public async Task ChangeUser_Should_Call_Admin_Endpoint() await client.Credentials.ChangeUserAsync(userKey, new ChangeCredentialRequest() { NewSecret = "uauth" }); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/change", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/change", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] public async Task RevokeUser_Should_Call_Admin_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = true, Status = 200 }); var client = CreateCredentialClient(); var userKey = UserKey.FromString("user-1"); await client.Credentials.RevokeUserAsync(userKey, new RevokeCredentialRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/revoke", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/credentials/revoke", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientEventConsistencyTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientEventConsistencyTests.cs index 096f82bc..0965356b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientEventConsistencyTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientEventConsistencyTests.cs @@ -1,14 +1,13 @@ using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; -using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Client.Services; using CodeBeam.UltimateAuth.Users.Contracts; using AwesomeAssertions; using Microsoft.Extensions.Options; using Moq; +using CodeBeam.UltimateAuth.Client.Abstractions; namespace CodeBeam.UltimateAuth.Tests.Unit; @@ -28,20 +27,29 @@ public class UAuthClientEventConsistencyTests private void Respond(int status, bool ok = true) { + var response = new UAuthTransportResult + { + Ok = ok, + Status = status + }; + _request.Setup(x => x.SendJsonAsync( - It.IsAny(), It.IsAny())) - .ReturnsAsync(new UAuthTransportResult - { - Ok = ok, - Status = status - }); + It.IsAny(), + It.IsAny(), + It.IsAny())) + .ReturnsAsync(response); + + _request.Setup(x => x.SendJsonAsync( + It.IsAny(), + It.IsAny(), + UAuthRequestAuthentication.Recoverable, + It.IsAny())) + .ReturnsAsync(response); } private void AssertNoEvents() { - _events.Verify( - x => x.PublishAsync(It.IsAny()), - Times.Never); + _events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); } [Theory] @@ -126,13 +134,11 @@ public async Task Credential_Should_Not_Publish_When_Response_Is_Invalid(string [Theory] [InlineData("Change")] [InlineData("CompleteReset")] - public async Task Typed_Credential_Response_Should_Not_Publish_When_Body_Missing( - string operation) + public async Task Typed_Credential_Response_Should_Not_Publish_When_Body_Missing(string operation) { Respond(200); - var client = new UAuthCredentialClient( - _request.Object, _events.Object, _options); + var client = new UAuthCredentialClient(_request.Object, _events.Object, _options); Func act = operation switch { @@ -150,8 +156,7 @@ public async Task Identifier_Should_Not_Publish_On_Server_Error() { Respond(500, ok: false); - var client = new UAuthUserIdentifierClient( - _request.Object, _events.Object, _options); + var client = new UAuthUserIdentifierClient(_request.Object, _events.Object, _options); Func act = () => client.AddMyAsync(null!); @@ -191,8 +196,7 @@ public async Task Identifier_Should_Return_Failure_Without_Event_On_4xx() { Respond(409, ok: false); - var client = new UAuthUserIdentifierClient( - _request.Object, _events.Object, _options); + var client = new UAuthUserIdentifierClient(_request.Object, _events.Object, _options); var result = await client.AddMyAsync(null!); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientScopeIsolationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientScopeIsolationTests.cs new file mode 100644 index 00000000..9b9852c8 --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientScopeIsolationTests.cs @@ -0,0 +1,708 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Blazor.Extensions; +using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; +using CodeBeam.UltimateAuth.Client.Diagnostics; +using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Options; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.JSInterop; +using Moq; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public class UAuthClientScopeIsolationTests +{ + private static ServiceCollection CreateServices() + { + var services = new ServiceCollection(); + + services.AddLogging(); + + services.AddSingleton( + new ConfigurationBuilder().Build()); + + services.AddScoped( + _ => Mock.Of()); + + services.AddScoped( + _ => Mock.Of()); + + services.AddUltimateAuthClientBlazor(options => + { + options.ApplicationProfile = + UAuthApplicationProfile.BlazorServer; + + options.AutoRefresh.Background = true; + options.AutoRefresh.Reactive = true; + options.AutoRefresh.Proactive = true; + options.AutoRefresh.Interval = + TimeSpan.FromMinutes(5); + + options.AutoRefresh.RefreshBeforeExpiration = + TimeSpan.FromMinutes(1); + }); + + return services; + } + + private static ServiceProvider CreateProvider( + Action? configure = null) + { + var services = CreateServices(); + + configure?.Invoke(services); + + return services.BuildServiceProvider( + new ServiceProviderOptions + { + ValidateScopes = true, + ValidateOnBuild = true + }); + } + + private static AccessToken Token( + string value, + DateTimeOffset now, + TimeSpan? lifetime = null) + { + return new AccessToken + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = now + + (lifetime ?? TimeSpan.FromMinutes(10)) + }; + } + + [Theory] + [InlineData(typeof(IUAuthTokenStore))] + [InlineData(typeof(IUAuthRefreshCoordinator))] + [InlineData(typeof(IUAuthRefreshExecutor))] + [InlineData(typeof(UAuthRefreshSchedule))] + [InlineData(typeof(IUAuthRequestRecovery))] + [InlineData(typeof(IUAuthStateManager))] + [InlineData(typeof(IUAuthClientEvents))] + [InlineData(typeof(IUAuthClientBootstrapper))] + [InlineData(typeof(IUAuthClient))] + [InlineData(typeof(IUAuthRequestClient))] + [InlineData(typeof(UAuthRequestClient))] + [InlineData(typeof(IUAuthResourceRequestClient))] + [InlineData(typeof(IUAuthRefreshTransport))] + [InlineData(typeof(ISessionCoordinator))] + [InlineData(typeof(UAuthClientDiagnostics))] + [InlineData(typeof(AuthenticationStateProvider))] + public void Authentication_Services_Should_Be_Scoped( + Type serviceType) + { + var services = CreateServices(); + + var registrations = services + .Where(x => x.ServiceType == serviceType) + .ToArray(); + + registrations.Should().NotBeEmpty(); + + registrations.Should().OnlyContain( + x => x.Lifetime == ServiceLifetime.Scoped); + } + + [Theory] + [InlineData(typeof(IUAuthTokenStore))] + [InlineData(typeof(IUAuthRefreshCoordinator))] + [InlineData(typeof(IUAuthRefreshExecutor))] + [InlineData(typeof(UAuthRefreshSchedule))] + [InlineData(typeof(IUAuthRequestRecovery))] + [InlineData(typeof(IUAuthStateManager))] + [InlineData(typeof(IUAuthClientEvents))] + [InlineData(typeof(IUAuthClientBootstrapper))] + [InlineData(typeof(IUAuthClient))] + [InlineData(typeof(IUAuthRequestClient))] + [InlineData(typeof(UAuthRequestClient))] + [InlineData(typeof(IUAuthResourceRequestClient))] + [InlineData(typeof(IUAuthRefreshTransport))] + [InlineData(typeof(ISessionCoordinator))] + [InlineData(typeof(UAuthClientDiagnostics))] + [InlineData(typeof(AuthenticationStateProvider))] + public async Task Authentication_Services_Should_Be_Isolated_Per_Scope(Type serviceType) + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var firstA = scopeA.ServiceProvider + .GetRequiredService(serviceType); + + var secondA = scopeA.ServiceProvider + .GetRequiredService(serviceType); + + var firstB = scopeB.ServiceProvider + .GetRequiredService(serviceType); + + var secondB = scopeB.ServiceProvider + .GetRequiredService(serviceType); + + firstA.Should().BeSameAs(secondA); + + firstB.Should().BeSameAs(secondB); + + firstA.Should().NotBeSameAs(firstB); + } + + [Fact] + public async Task Client_Service_Graph_Should_Pass_Scope_Validation() + { + await using var provider = CreateProvider(); + provider.Should().NotBeNull(); + } + + [Theory] + [InlineData(typeof(IUAuthTokenStore))] + [InlineData(typeof(IUAuthRefreshCoordinator))] + [InlineData(typeof(IUAuthRefreshExecutor))] + [InlineData(typeof(IUAuthStateManager))] + [InlineData(typeof(ISessionCoordinator))] + public async Task Authentication_Services_Should_Not_Resolve_From_Root(Type serviceType) + { + await using var provider = CreateProvider(); + + Action act = () => provider.GetRequiredService(serviceType); + + act.Should().Throw(); + } + + [Fact] + public async Task Authentication_In_One_Scope_Should_Not_Affect_Another() + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var clock = provider + .GetRequiredService(); + + var initialB = storeB.Capture(); + + storeA.Replace(Token( + "alice-token", + clock.UtcNow)); + + storeA.Capture().Token!.Token + .Should().Be("alice-token"); + + storeB.Capture().Should().Be(initialB); + + storeB.Capture().Token.Should().BeNull(); + } + + [Fact] + public async Task Token_Rotation_Should_Be_Isolated_Per_Scope() + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var clock = provider + .GetRequiredService(); + + storeA.Replace(Token( + "alice-token", + clock.UtcNow)); + + storeB.Replace(Token( + "bob-token", + clock.UtcNow)); + + var expectedA = storeA.Capture(); + + var expectedB = storeB.Capture(); + + storeA.TryRotate( + expectedA, + Token("alice-rotated-token", clock.UtcNow)) + .Should().BeTrue(); + + var currentA = storeA.Capture(); + + currentA.Token!.Token + .Should().Be("alice-rotated-token"); + + currentA.Generation.Should().Be( + expectedA.Generation + 1); + + currentA.Epoch.Should().Be(expectedA.Epoch); + + storeB.Capture().Should().Be(expectedB); + } + + [Fact] + public async Task Logout_Should_Not_Clear_Another_Scope() + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var clock = provider + .GetRequiredService(); + + storeA.Replace(Token( + "alice-token", + clock.UtcNow)); + + storeB.Replace(Token( + "bob-token", + clock.UtcNow)); + + var expectedA = storeA.Capture(); + + var expectedB = storeB.Capture(); + + storeA.Clear(); + + var currentA = storeA.Capture(); + + currentA.Token.Should().BeNull(); + + currentA.Epoch.Should().Be( + expectedA.Epoch + 1); + + storeB.Capture().Should().Be(expectedB); + } + + [Fact] + public async Task Authentication_Schedule_Should_Be_Isolated_Per_Scope() + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var scheduleA = scopeA.ServiceProvider + .GetRequiredService(); + + var scheduleB = scopeB.ServiceProvider + .GetRequiredService(); + + var snapshotA = storeA.Capture(); + + var snapshotB = storeB.Capture(); + + scheduleA.MarkAuthenticated(snapshotA); + + scheduleA.IsAuthenticated(snapshotA) + .Should().BeTrue(); + + scheduleA.GetNextRefreshAt(snapshotA) + .Should().NotBeNull(); + + scheduleB.IsAuthenticated(snapshotB) + .Should().BeFalse(); + + scheduleB.GetNextRefreshAt(snapshotB) + .Should().BeNull(); + } + + [Fact] + public async Task Jwt_Schedules_Should_Use_Their_Own_Credentials() + { + await using var provider = CreateProvider(); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var clock = provider + .GetRequiredService(); + + var now = clock.UtcNow; + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var scheduleA = scopeA.ServiceProvider + .GetRequiredService(); + + var scheduleB = scopeB.ServiceProvider + .GetRequiredService(); + + storeA.Replace(Token( + "alice-token", + now, + TimeSpan.FromMinutes(10))); + + storeB.Replace(Token( + "bob-token", + now, + TimeSpan.FromMinutes(20))); + + var snapshotA = storeA.Capture(); + + var snapshotB = storeB.Capture(); + + scheduleA.MarkAuthenticated(snapshotA); + + scheduleB.MarkAuthenticated(snapshotB); + + scheduleA.GetNextRefreshAt(snapshotA) + .Should().Be(now.AddMinutes(9)); + + scheduleB.GetNextRefreshAt(snapshotB) + .Should().Be(now.AddMinutes(19)); + } + + [Fact] + public async Task Concurrent_Refreshes_From_Different_Scopes_Should_Not_Share_Flight() + { + var executorA = new Mock(); + + var executorB = new Mock(); + + var executorCount = 0; + + await using var provider = CreateProvider(services => + { + services.RemoveAll(); + + services.AddScoped(_ => + Interlocked.Increment(ref executorCount) == 1 + ? executorA.Object + : executorB.Object); + }); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var coordinatorA = scopeA.ServiceProvider + .GetRequiredService(); + + var coordinatorB = scopeB.ServiceProvider + .GetRequiredService(); + + var clock = provider + .GetRequiredService(); + + storeA.Replace(Token( + "alice-token", + clock.UtcNow)); + + storeB.Replace(Token( + "bob-token", + clock.UtcNow)); + + var expectedA = storeA.Capture(); + + var expectedB = storeB.Capture(); + + var pendingA = + new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var pendingB = + new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + executorA + .Setup(x => x.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedA)) + .Returns(pendingA.Task); + + executorB + .Setup(x => x.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedB)) + .Returns(pendingB.Task); + + var ct = TestContext.Current.CancellationToken; + + var refreshA = coordinatorA.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Manual, + expectedA, + ct); + + var refreshB = coordinatorB.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Manual, + expectedB, + ct); + + try + { + executorA.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedA), + Times.Once); + + executorB.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedB), + Times.Once); + + refreshA.IsCompleted.Should().BeFalse(); + + refreshB.IsCompleted.Should().BeFalse(); + + storeA.TryRotate( + expectedA, + Token("alice-rotated", clock.UtcNow)) + .Should().BeTrue(); + + pendingA.SetResult(new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Rotated + }); + + var resultA = await refreshA.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + resultA.IsSuccess.Should().BeTrue(); + + refreshB.IsCompleted.Should().BeFalse(); + + storeB.Capture().Should().Be(expectedB); + + pendingB.SetResult(new RefreshResult + { + IsSuccess = false, + Status = 429, + Outcome = RefreshOutcome.None, + ErrorCode = "rate_limited", + RetryAfter = TimeSpan.FromSeconds(30) + }); + + var resultB = await refreshB.WaitAsync( + TimeSpan.FromSeconds(5), + ct); + + resultB.Status.Should().Be(429); + + storeA.Capture().Token!.Token + .Should().Be("alice-rotated"); + + storeB.Capture().Token!.Token + .Should().Be("bob-token"); + } + finally + { + pendingA.TrySetResult(new RefreshResult + { + IsSuccess = true, + Status = 204 + }); + + pendingB.TrySetResult(new RefreshResult + { + IsSuccess = true, + Status = 204 + }); + } + } + + [Fact] + public async Task Refresh_Rate_Limit_Should_Not_Leak_Between_Scopes() + { + var transportA = new Mock(); + + var transportB = new Mock(); + + var transportCount = 0; + + transportA + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "120" + }); + + transportB + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + await using var provider = CreateProvider(services => + { + services.RemoveAll(); + + services.AddScoped(_ => + Interlocked.Increment(ref transportCount) == 1 + ? transportA.Object + : transportB.Object); + }); + + await using var scopeA = + provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var executorA = scopeA.ServiceProvider + .GetRequiredService(); + + var executorB = scopeB.ServiceProvider + .GetRequiredService(); + + var storeA = scopeA.ServiceProvider + .GetRequiredService(); + + var storeB = scopeB.ServiceProvider + .GetRequiredService(); + + var clock = provider + .GetRequiredService(); + + storeA.Replace(Token( + "alice-token", + clock.UtcNow)); + + storeB.Replace(Token( + "bob-token", + clock.UtcNow)); + + var expectedA = storeA.Capture(); + + var expectedB = storeB.Capture(); + + var resultA = await executorA.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedA); + + resultA.Status.Should().Be(429); + + var resultB = await executorB.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expectedB); + + resultB.IsSuccess.Should().BeTrue(); + + resultB.Status.Should().Be(204); + + var throttledA = await executorA.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expectedA); + + throttledA.Status.Should().Be(429); + + transportA.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + transportB.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + storeA.Capture().Should().Be(expectedA); + + storeB.Capture().Should().Be(expectedB); + } + + [Fact] + public async Task Disposing_One_Scope_Should_Not_Dispose_Another_Coordinator() + { + await using var provider = CreateProvider(); + + var scopeA = provider.CreateAsyncScope(); + + await using var scopeB = + provider.CreateAsyncScope(); + + var coordinatorA = scopeA.ServiceProvider + .GetRequiredService(); + + var coordinatorB = scopeB.ServiceProvider + .GetRequiredService(); + + await scopeA.DisposeAsync(); + + var ct = TestContext.Current.CancellationToken; + + Func startA = () => + coordinatorA.StartAsync(ct); + + await startA.Should() + .ThrowAsync(); + + Func startB = () => + coordinatorB.StartAsync(ct); + + await startB.Should() + .NotThrowAsync(); + + await coordinatorB.StopAsync(); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientSessionTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientSessionTests.cs index deaa0861..1857fa79 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientSessionTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientSessionTests.cs @@ -1,8 +1,6 @@ using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; -using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; using CodeBeam.UltimateAuth.Client.Services; using CodeBeam.UltimateAuth.Core.Contracts; @@ -11,6 +9,7 @@ using Microsoft.Extensions.Options; using Moq; using System.Text.Json; +using CodeBeam.UltimateAuth.Client.Abstractions; namespace CodeBeam.UltimateAuth.Tests.Unit; @@ -41,8 +40,7 @@ private IUAuthClient CreateClient() resource: Mock.Of()); } - private static UAuthTransportResult Success() - => new() { Ok = true, Status = 200 }; + private static UAuthTransportResult Success() => new() { Ok = true, Status = 200 }; private static UAuthTransportResult SuccessJson(T body) => new() @@ -59,12 +57,12 @@ public async Task GetMyChains_Should_Call_Correct_Endpoint() new List(), 0, 1, 10, null, false); - _request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + _request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); await client.Sessions.GetMyChainsAsync(); - _request.Verify(x => x.SendJsonAsync("/auth/me/sessions/chains", It.IsAny()), Times.Once); + _request.Verify(x => x.SendJsonAsync("/auth/me/sessions/chains", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -105,38 +103,60 @@ public async Task GetUserChainDetail_Should_Call_Correct_Endpoint() [Fact] public async Task RevokeMyChain_Should_Publish_Event_When_CurrentChain() { + var chainId = SessionChainId.New(); + var response = new RevokeResult { CurrentChain = true }; - _request.Setup(x => x.SendJsonAsync(It.IsAny())) + _request.Setup(x => x.SendJsonAsync( + $"/auth/me/sessions/chains/{chainId.Value}/revoke", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); - var chainId = SessionChainId.From(Guid.NewGuid()); - await client.Sessions.RevokeMyChainAsync(chainId); + var result = await client.Sessions.RevokeMyChainAsync(chainId); - _events.Verify(x => x.PublishAsync(It.Is(e => e.Type == UAuthStateEvent.SessionRevoked)), Times.Once); + result.IsSuccess.Should().BeTrue(); + result.Value!.CurrentChain.Should().BeTrue(); + + _events.Verify(x => x.PublishAsync( + It.Is(e => + e.Type == UAuthStateEvent.SessionRevoked)), + Times.Once); } [Fact] public async Task RevokeMyChain_Should_NOT_Publish_Event_When_Not_CurrentChain() { + var chainId = SessionChainId.New(); + var response = new RevokeResult { CurrentChain = false }; - _request.Setup(x => x.SendJsonAsync(It.IsAny())) + _request.Setup(x => x.SendJsonAsync( + $"/auth/me/sessions/chains/{chainId.Value}/revoke", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); - var chainId = SessionChainId.From(Guid.NewGuid()); - await client.Sessions.RevokeMyChainAsync(chainId); - _events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); + var result = await client.Sessions.RevokeMyChainAsync(chainId); + + result.IsSuccess.Should().BeTrue(); + result.Value!.CurrentChain.Should().BeFalse(); + + _events.Verify( + x => x.PublishAsync(It.IsAny()), + Times.Never); } [Fact] @@ -211,14 +231,14 @@ public async Task GetUserChains_Should_Call_Admin_Endpoint() new List(), 0, 1, 10, null, false); - _request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + _request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateClient(); var userKey = UserKey.FromString("user-1"); await client.Sessions.GetUserChainsAsync(userKey); - _request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/sessions/chains", It.IsAny()), Times.Once); + _request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/sessions/chains", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -251,7 +271,13 @@ public async Task RevokeUserRoot_Should_Call_Correct_Endpoint() [Fact] public async Task RevokeMyChain_Should_NOT_Publish_Event_When_Response_Body_Missing() { - _request.Setup(x => x.SendJsonAsync(It.IsAny())) + var chainId = SessionChainId.New(); + + _request.Setup(x => x.SendJsonAsync( + $"/auth/me/sessions/chains/{chainId.Value}/revoke", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(new UAuthTransportResult { Ok = true, @@ -260,7 +286,6 @@ public async Task RevokeMyChain_Should_NOT_Publish_Event_When_Response_Body_Miss }); var client = CreateClient(); - var chainId = SessionChainId.New(); await FluentActions .Invoking(() => client.Sessions.RevokeMyChainAsync(chainId)) @@ -272,43 +297,65 @@ await FluentActions Times.Never); } - [Fact] - public async Task RevokeMyChain_Should_Not_Publish_Event_On_4xx() + [Theory] + [InlineData(400)] + [InlineData(401)] + [InlineData(403)] + [InlineData(404)] + [InlineData(409)] + [InlineData(429)] + public async Task RevokeMyChain_Should_Not_Publish_Event_On_4xx(int status) { - _request.Setup(x => x.SendJsonAsync(It.IsAny())) + var chainId = SessionChainId.New(); + + _request.Setup(x => x.SendJsonAsync( + $"/auth/me/sessions/chains/{chainId.Value}/revoke", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(new UAuthTransportResult { Ok = false, - Status = 403 + Status = status }); var client = CreateClient(); - var result = await client.Sessions.RevokeMyChainAsync( - SessionChainId.New()); + var result = await client.Sessions.RevokeMyChainAsync(chainId); result.IsSuccess.Should().BeFalse(); - result.Status.Should().Be(403); + result.Status.Should().Be(status); + result.Value.Should().BeNull(); _events.Verify( x => x.PublishAsync(It.IsAny()), Times.Never); } - [Fact] - public async Task RevokeMyChain_Should_Not_Publish_Event_On_5xx() + [Theory] + [InlineData(500)] + [InlineData(502)] + [InlineData(503)] + [InlineData(504)] + public async Task RevokeMyChain_Should_Not_Publish_Event_On_5xx(int status) { - _request.Setup(x => x.SendJsonAsync(It.IsAny())) + var chainId = SessionChainId.New(); + + _request.Setup(x => x.SendJsonAsync( + $"/auth/me/sessions/chains/{chainId.Value}/revoke", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(new UAuthTransportResult { Ok = false, - Status = 500 + Status = status }); var client = CreateClient(); Func act = () => - client.Sessions.RevokeMyChainAsync(SessionChainId.New()); + client.Sessions.RevokeMyChainAsync(chainId); await act.Should().ThrowAsync(); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserIdentifiersTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserIdentifiersTests.cs index def61741..419adf6e 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserIdentifiersTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserIdentifiersTests.cs @@ -16,12 +16,12 @@ public async Task GetMy_Should_Call_Correct_Endpoint() new List(), 0, 1, 10, null, false); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateIdentifierClient(); await client.Identifiers.GetMyAsync(); - Request.Verify(x => x.SendJsonAsync("/auth/me/identifiers/get", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/me/identifiers/get", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -29,7 +29,7 @@ public async Task AddMy_Should_Publish_Event_On_Success() { var request = new AddUserIdentifierRequest() { Value = "uauth" }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -45,7 +45,7 @@ public async Task AddMy_Should_Publish_Event_On_Success() [Fact] public async Task AddMy_Should_NOT_Publish_Event_On_Failure() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Failure()); var client = CreateIdentifierClient(); @@ -58,7 +58,7 @@ public async Task UpdateMy_Should_Publish_Event_On_Success() { var request = new UpdateUserIdentifierRequest() { NewValue = "uauth" }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -69,7 +69,7 @@ public async Task UpdateMy_Should_Publish_Event_On_Success() [Fact] public async Task SetMyPrimary_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -80,7 +80,7 @@ public async Task SetMyPrimary_Should_Publish_Event_On_Success() [Fact] public async Task UnsetMyPrimary_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -91,7 +91,7 @@ public async Task UnsetMyPrimary_Should_Publish_Event_On_Success() [Fact] public async Task VerifyMy_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -102,7 +102,7 @@ public async Task VerifyMy_Should_Publish_Event_On_Success() [Fact] public async Task DeleteMy_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); @@ -119,12 +119,12 @@ public async Task GetUser_Should_Call_Admin_Endpoint() new List(), 0, 1, 10, null, false); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateIdentifierClient(); await client.Identifiers.GetUserAsync(userKey); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/get", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/get", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -132,12 +132,12 @@ public async Task AddUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.AddUserAsync(userKey, new AddUserIdentifierRequest() { Value = "uauth"}); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey}/identifiers/add", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey}/identifiers/add", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -145,12 +145,12 @@ public async Task DeleteUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.DeleteUserAsync(userKey, new DeleteUserIdentifierRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey}/identifiers/delete", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey}/identifiers/delete", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -158,12 +158,12 @@ public async Task UpdateUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.UpdateUserAsync(userKey, new UpdateUserIdentifierRequest() { NewValue = "uauth" }); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/update", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/update", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); Events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); } @@ -172,12 +172,12 @@ public async Task SetUserPrimary_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.SetUserPrimaryAsync(userKey, new SetPrimaryUserIdentifierRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/set-primary", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/set-primary", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -185,12 +185,12 @@ public async Task UnsetUserPrimary_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.UnsetUserPrimaryAsync(userKey, new UnsetPrimaryUserIdentifierRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/unset-primary", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/unset-primary", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); Events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); } @@ -199,12 +199,12 @@ public async Task VerifyUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateIdentifierClient(); await client.Identifiers.VerifyUserAsync(userKey, new VerifyUserIdentifierRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/verify", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/identifiers/verify", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); Events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserTests.cs index 0fed442b..65bf8914 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthClientUserTests.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; @@ -21,7 +20,7 @@ public async Task GetMe_Should_Call_Correct_Endpoint() UserKey = UserKey.FromString("user-1") }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); @@ -29,7 +28,7 @@ public async Task GetMe_Should_Call_Correct_Endpoint() Request.Verify(x => x.SendJsonAsync( "/auth/me/profile/get", - It.Is(o => o is GetProfileRequest && ((GetProfileRequest)o).ProfileKey == null)), Times.Once); + It.Is(o => o is GetProfileRequest && ((GetProfileRequest)o).ProfileKey == null), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -37,7 +36,7 @@ public async Task UpdateMe_Should_Publish_Event_On_Success() { var request = new UpdateProfileRequest(); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateUserClient(); @@ -52,7 +51,7 @@ public async Task UpdateMe_Should_Publish_Event_On_Success() [Fact] public async Task UpdateMe_Should_NOT_Publish_Event_On_Failure() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = false, Status = 400 }); var client = CreateUserClient(); @@ -63,12 +62,30 @@ public async Task UpdateMe_Should_NOT_Publish_Event_On_Failure() [Fact] public async Task DeleteMe_Should_Publish_Event_On_Success() { - Request.Setup(x => x.SendJsonAsync(It.IsAny())) + Request.Setup(x => x.SendJsonAsync( + "/auth/me/delete", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny())) .ReturnsAsync(Success()); var client = CreateUserClient(); - await client.Users.DeleteMeAsync(); - Events.Verify(x => x.PublishAsync(It.Is(e => e.Type == UAuthStateEvent.UserDeleted)), Times.Once); + + var result = await client.Users.DeleteMeAsync(); + + result.IsSuccess.Should().BeTrue(); + + Events.Verify(x => x.PublishAsync( + It.Is(e => + e.Type == UAuthStateEvent.UserDeleted)), + Times.Once); + + Request.Verify(x => x.SendJsonAsync( + "/auth/me/delete", + null, + UAuthRequestAuthentication.Recoverable, + It.IsAny()), + Times.Once); } [Fact] @@ -78,34 +95,34 @@ public async Task Query_Should_Call_Admin_Endpoint() new List(), 0, 1, 10, null, false); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); await client.Users.QueryAsync(new UserQuery()); - Request.Verify(x => x.SendJsonAsync("/auth/admin/users/query", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/admin/users/query", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] public async Task Create_Should_Call_Public_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new UserCreateResult() { IsSuccess = true })); var client = CreateUserClient(); await client.Users.CreateAsync(new CreateUserRequest()); - Request.Verify(x => x.SendJsonAsync("/auth/users/create", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/users/create", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] public async Task CreateAsAdmin_Should_Call_Admin_Endpoint() { - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new UserCreateResult() { IsSuccess = true})); var client = CreateUserClient(); await client.Users.CreateAsAdminAsync(new CreateUserRequest()); - Request.Verify(x => x.SendJsonAsync("/auth/admin/users/create", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/admin/users/create", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -113,7 +130,7 @@ public async Task ChangeMyStatus_Should_Publish_Event_On_Success() { var request = new ChangeUserStatusSelfRequest() { NewStatus = SelfAssignableUserStatus.Active }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new UserStatusChangeResult() { IsSuccess = true })); var client = CreateUserClient(); @@ -130,12 +147,12 @@ public async Task ChangeUserStatus_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new UserStatusChangeResult() { IsSuccess = true })); var client = CreateUserClient(); await client.Users.ChangeUserStatusAsync(userKey, new ChangeUserStatusAdminRequest() { NewStatus = AdminAssignableUserStatus.Active }); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/status", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/status", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -143,12 +160,12 @@ public async Task DeleteUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(new UserDeleteResult() { IsSuccess = true, Mode = DeleteMode.Soft })); var client = CreateUserClient(); await client.Users.DeleteUserAsync(userKey, new DeleteUserRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/delete", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/delete", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -161,7 +178,7 @@ public async Task GetUser_Should_Call_Admin_Endpoint() UserKey = userKey }; - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); @@ -169,7 +186,7 @@ public async Task GetUser_Should_Call_Admin_Endpoint() Request.Verify(x => x.SendJsonAsync( $"/auth/admin/users/{userKey.Value}/profile/get", - It.Is(o => o is GetProfileRequest && ((GetProfileRequest)o).ProfileKey == null)), Times.Once); + It.Is(o => o is GetProfileRequest && ((GetProfileRequest)o).ProfileKey == null), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -177,12 +194,12 @@ public async Task UpdateUser_Should_Call_Admin_Endpoint() { var userKey = UserKey.FromString("user-1"); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(Success()); var client = CreateUserClient(); await client.Users.UpdateUserProfileAsync(userKey, new UpdateProfileRequest()); - Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/profile/update", It.IsAny()), Times.Once); + Request.Verify(x => x.SendJsonAsync($"/auth/admin/users/{userKey.Value}/profile/update", It.IsAny(), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -192,12 +209,12 @@ public async Task Query_Should_Create_Default_Query_When_Null() new List(), 0, 1, 10, null, false); - Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny())) + Request.Setup(x => x.SendJsonAsync(It.IsAny(), It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); await client.Users.QueryAsync(null!); - Request.Verify(x => x.SendJsonAsync("/auth/admin/users/query", It.Is(o => o is UserQuery)), Times.Once); + Request.Verify(x => x.SendJsonAsync("/auth/admin/users/query", It.Is(o => o is UserQuery), UAuthRequestAuthentication.Recoverable), Times.Once); } [Fact] @@ -212,7 +229,7 @@ public async Task Query_Should_Use_Given_Query() Request.Setup(x => x.SendJsonAsync( It.IsAny(), - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); @@ -225,7 +242,7 @@ public async Task Query_Should_Use_Given_Query() Request.Verify(x => x.SendJsonAsync( "/auth/admin/users/query", - It.Is(o => ReferenceEquals(o, query))), + It.Is(o => ReferenceEquals(o, query)), UAuthRequestAuthentication.Recoverable), Times.Once); } @@ -240,7 +257,7 @@ public async Task ChangeMyStatus_Should_Not_Publish_Event_When_Body_Missing() Request.Setup(x => x.SendJsonAsync( It.IsAny(), - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(new UAuthTransportResult { Ok = true, @@ -250,14 +267,11 @@ public async Task ChangeMyStatus_Should_Not_Publish_Event_When_Body_Missing() var client = CreateUserClient(); - Func act = () => - client.Users.ChangeMyStatusAsync(request); + Func act = () => client.Users.ChangeMyStatusAsync(request); await act.Should().ThrowAsync(); - Events.Verify( - x => x.PublishAsync(It.IsAny()), - Times.Never); + Events.Verify(x => x.PublishAsync(It.IsAny()), Times.Never); } [Fact] @@ -337,7 +351,7 @@ public async Task GetAuthenticationLockout_CallsAdminEndpoint() Request.Setup(x => x.SendJsonAsync( It.IsAny(), - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); @@ -350,7 +364,7 @@ public async Task GetAuthenticationLockout_CallsAdminEndpoint() Request.Verify(x => x.SendJsonAsync( $"/auth/admin/users/{userKey.Value}/authentication/lockout/get", - It.Is(x => ReferenceEquals(x, request))), + It.Is(x => ReferenceEquals(x, request)), UAuthRequestAuthentication.Recoverable), Times.Once); } @@ -374,7 +388,7 @@ public async Task UnlockAuthentication_CallsAdminEndpoint() Request.Setup(x => x.SendJsonAsync( It.IsAny(), - It.IsAny())) + It.IsAny(), UAuthRequestAuthentication.Recoverable)) .ReturnsAsync(SuccessJson(response)); var client = CreateUserClient(); @@ -387,7 +401,7 @@ public async Task UnlockAuthentication_CallsAdminEndpoint() Request.Verify(x => x.SendJsonAsync( $"/auth/admin/users/{userKey.Value}/authentication/unlock", - It.Is(x => ReferenceEquals(x, request))), + It.Is(x => ReferenceEquals(x, request)), UAuthRequestAuthentication.Recoverable), Times.Once); Events.Verify(x => diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthFlowClientTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthFlowClientTests.cs index f3b7b7c5..2760b609 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthFlowClientTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthFlowClientTests.cs @@ -1,6 +1,5 @@ using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; @@ -26,7 +25,8 @@ private UAuthFlowClient CreateClient( Mock? requestMock = null, UAuthClientDiagnostics? diagnostics = null, IUAuthTokenStore? tokenStore = null, - IUAuthClientEvents? clientEvents = null) + IUAuthClientEvents? clientEvents = null, + bool backgroundRefreshDue = false) { var request = requestMock ?? new Mock(); @@ -37,8 +37,7 @@ private UAuthFlowClient CreateClient( deviceIdProvider .Setup(x => x.GetOrCreateAsync(It.IsAny())) - .Returns(new ValueTask( - DeviceId.Create("device-1234567890123456"))); + .Returns(new ValueTask(DeviceId.Create("device-1234567890123456"))); returnUrlProvider .Setup(x => x.GetCurrentUrl()) @@ -58,14 +57,26 @@ private UAuthFlowClient CreateClient( } }); + var actualEvents = clientEvents ?? events.Object; + var actualDiagnostics = diagnostics ?? new UAuthClientDiagnostics(); + var actualStore = tokenStore ?? new InMemoryUAuthTokenStore(); + + var refreshCoordinator = CreateRefreshCoordinator( + request.Object, + actualEvents, + actualStore, + actualDiagnostics, + "/auth/refresh", + backgroundRefreshDue); + return new UAuthFlowClient( request.Object, - clientEvents ?? events.Object, + actualEvents, deviceProvider.Object, returnUrlProvider.Object, options, - diagnostics ?? new UAuthClientDiagnostics(), - tokenStore ?? new InMemoryUAuthTokenStore()); + actualStore, + refreshCoordinator); } private static AccessToken CreateStoredToken() @@ -326,8 +337,8 @@ public async Task TryLogin_Should_Throw_When_CredentialPost_Disabled() Mock.Of(), Mock.Of(), options, - new UAuthClientDiagnostics(), - new InMemoryUAuthTokenStore()); + new InMemoryUAuthTokenStore(), + Mock.Of()); Func act = async () => await client.TryLoginAsync(new LoginRequest(), UAuthSubmitMode.TryOnly); await act.Should().ThrowAsync(); @@ -495,12 +506,13 @@ public async Task Logout_Should_Respect_Navigate_Option_And_Publish_Event(bool n [Fact] public async Task Refresh_Should_Not_Mark_Manual_When_Auto() { - var mock = new Mock(); + var request = new Mock(); + var diagnostics = new UAuthClientDiagnostics(); - mock.Setup(x => x.SendFormAsync( - It.IsAny(), - It.IsAny>(), - It.IsAny())) + request.Setup(x => x.SendFormAsync( + It.IsAny(), + It.IsAny>(), + It.IsAny())) .ReturnsAsync(new UAuthTransportResult { Ok = true, @@ -508,9 +520,18 @@ public async Task Refresh_Should_Not_Mark_Manual_When_Auto() RefreshOutcome = "success" }); - var client = CreateFlowClient(mock); + var client = CreateClient(request, diagnostics, backgroundRefreshDue: true); var result = await client.RefreshAsync(isAuto: true); + result.IsSuccess.Should().BeTrue(); + + diagnostics.ManualRefreshCount.Should().Be(0); + + request.Verify(x => x.SendFormAsync( + "/auth/refresh", + It.IsAny>(), + It.IsAny()), + Times.Once); } [Fact] @@ -629,8 +650,8 @@ public async Task BeginPkce_Should_Throw_When_Disabled() Mock.Of(), Mock.Of(), options, - new UAuthClientDiagnostics(), - new InMemoryUAuthTokenStore()); + new InMemoryUAuthTokenStore(), + Mock.Of()); Func act = async () => await client.BeginPkceAsync(); await act.Should().ThrowAsync(); @@ -736,8 +757,8 @@ public async Task BeginPkce_Should_AutoRedirect_When_Enabled() Mock.Of(), Mock.Of(), options, - new UAuthClientDiagnostics(), - new InMemoryUAuthTokenStore()); + new InMemoryUAuthTokenStore(), + Mock.Of()); await client.BeginPkceAsync(); mock.Verify(x => x.NavigateAsync("/auth/hub/login", It.IsAny>(), It.IsAny()), Times.Once); @@ -929,8 +950,8 @@ public async Task CompletePkce_Should_Throw_When_Pkce_Disabled() Mock.Of(), Mock.Of(), options, - new UAuthClientDiagnostics(), - new InMemoryUAuthTokenStore()); + new InMemoryUAuthTokenStore(), + Mock.Of()); Func act = async () => await client.CompletePkceLoginAsync(new PkceCompleteRequest { @@ -1053,7 +1074,10 @@ public async Task Refresh_Should_Record_Correct_Diagnostic_Outcome(string outcom RefreshOutcome = outcomeHeader }); - var client = CreateClient(request, diagnostics); + var client = CreateClient( + request, + diagnostics, + backgroundRefreshDue: true); var result = await client.RefreshAsync(isAuto: true); @@ -1073,8 +1097,13 @@ public async Task Refresh_Should_Record_Correct_Diagnostic_Outcome(string outcom .Be(expectedOutcome == RefreshOutcome.ReauthRequired ? 1 : 0); diagnostics.RefreshSuccessCount.Should().Be(0); - diagnostics.ManualRefreshCount.Should().Be(0); + + request.Verify(x => x.SendFormAsync( + "/auth/refresh", + It.IsAny>(), + It.IsAny()), + Times.Once); } [Fact] @@ -1152,21 +1181,33 @@ public async Task Refresh_Should_Record_ReauthRequired_On_Failed_Response() .ReturnsAsync(new UAuthTransportResult { Ok = false, - Status = 400, + Status = 401, RefreshOutcome = "reauth-required" }); - var client = CreateClient(request, diagnostics); + var client = CreateClient( + request, + diagnostics, + backgroundRefreshDue: true); var result = await client.RefreshAsync(isAuto: true); result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(401); result.Outcome.Should().Be(RefreshOutcome.ReauthRequired); diagnostics.RefreshReauthRequiredCount.Should().Be(1); - diagnostics.RefreshSuccessCount.Should().Be(0); diagnostics.RefreshRotatedCount.Should().Be(0); + diagnostics.RefreshNoOpCount.Should().Be(0); + diagnostics.RefreshTouchedCount.Should().Be(0); + diagnostics.ManualRefreshCount.Should().Be(0); + + request.Verify(x => x.SendFormAsync( + "/auth/refresh", + It.IsAny>(), + It.IsAny()), + Times.Once); } [Theory] @@ -1906,4 +1947,31 @@ await act.Should() It.IsAny()), Times.Never); } + + [Fact] + public async Task Refresh_Should_Skip_Auto_When_Not_Due() + { + var request = new Mock(); + var diagnostics = new UAuthClientDiagnostics(); + + var client = CreateClient( + request, + diagnostics, + backgroundRefreshDue: false); + + var result = await client.RefreshAsync(isAuto: true); + + result.IsSuccess.Should().BeFalse(); + result.Outcome.Should().Be(RefreshOutcome.None); + result.ErrorCode.Should().Be("refresh_not_due"); + + diagnostics.ManualRefreshCount.Should().Be(0); + diagnostics.RefreshSuccessCount.Should().Be(0); + + request.Verify(x => x.SendFormAsync( + It.IsAny(), + It.IsAny>(), + It.IsAny()), + Times.Never); + } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthLoginCompletionTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthLoginCompletionTests.cs index 671daefe..8e5b4055 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthLoginCompletionTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthLoginCompletionTests.cs @@ -1,6 +1,5 @@ using AwesomeAssertions; using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRecoveringRequestClientTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRecoveringRequestClientTests.cs new file mode 100644 index 00000000..a97f850b --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRecoveringRequestClientTests.cs @@ -0,0 +1,830 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.Options; +using Microsoft.JSInterop; +using Moq; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public sealed class UAuthRecoveringRequestClientTests +{ +#pragma warning disable BL0016 + + private const string Endpoint = "/auth/me/profile/update"; + private const string JsMethod = "uauth.postJson"; + + private readonly Mock _js = new(); + private readonly Mock _bootstrapper = new(); + private readonly Mock _recovery = new(); + private readonly InMemoryUAuthTokenStore _store = new(); + + public UAuthRecoveringRequestClientTests() + { + _bootstrapper + .Setup(x => x.EnsureStartedAsync( + It.IsAny())) + .Returns(Task.CompletedTask); + + _recovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(() => + new UAuthRequestPreparationResult( + _store.Capture())); + + _recovery + .Setup(x => x.RecoverAsync( + It.IsAny(), + It.IsAny())) + .ReturnsAsync((UAuthTokenSnapshot?)null); + } + + private UAuthRecoveringRequestClient CreateSut( + bool reactive = true) + { + var options = Options.Create(new UAuthClientOptions + { + AutoRefresh = new UAuthClientAutoRefreshOptions + { + Reactive = reactive + } + }); + + var raw = new UAuthRequestClient( + _js.Object, + _bootstrapper.Object, + options, + _store, + Mock.Of()); + + return new UAuthRecoveringRequestClient( + raw, + _recovery.Object, + _store, + options); + } + + private static AccessToken Token( + string value, + DateTimeOffset? expiresAt = null) + => new() + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = expiresAt ?? + DateTimeOffset.UtcNow.AddMinutes(10) + }; + + private static UAuthTransportResult Success() + => new() + { + Ok = true, + Status = 200 + }; + + private static UAuthTransportResult Challenge() + => new() + { + Ok = false, + Status = 401, + AuthRecovery = "challenge" + }; + + private void SetupResponse(UAuthTransportResult response) + { + _js.Setup(x => x.InvokeAsync( + JsMethod, + It.IsAny(), + It.IsAny())) + .ReturnsAsync(response); + } + + private void VerifyRequests(Times times) + { + _js.Verify(x => x.InvokeAsync( + JsMethod, + It.IsAny(), + It.IsAny()), + times); + } + + private void VerifyPreparation(Times times) + { + _recovery.Verify(x => x.PrepareAsync( + It.IsAny()), + times); + } + + private void VerifyRecovery(Times times) + { + _recovery.Verify(x => x.RecoverAsync( + It.IsAny(), + It.IsAny()), + times); + } + + private void SetupRotation(UAuthTokenSnapshot expected) + { + _recovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _store.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + return _store.Capture(); + }); + } + + private static T? ReadArgument( + object options, + string name) + { + return (T?)options.GetType() + .GetProperty(name)! + .GetValue(options); + } + + // -------------------------------------------------------- + // Request classification + // -------------------------------------------------------- + + [Theory] + [InlineData(200)] + [InlineData(401)] + [InlineData(429)] + public async Task Anonymous_Request_Should_Bypass_Recovery( + int status) + { + var response = new UAuthTransportResult + { + Ok = status == 200, + Status = status, + AuthRecovery = status == 401 + ? "challenge" + : null + }; + + SetupResponse(response); + + var result = await CreateSut().SendJsonAsync( + "/auth/users/create", + new { Name = "User" }, + UAuthRequestAuthentication.None, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(response); + + VerifyPreparation(Times.Never()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Legacy_Json_Overload_Should_Bypass_Recovery() + { + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + new { DisplayName = "Updated" }, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyPreparation(Times.Never()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Authenticated_Success_Should_Not_Recover() + { + _store.Replace(Token("old-token")); + + var response = Success(); + + SetupResponse(response); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(response); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Theory] + [InlineData(400)] + [InlineData(401)] + [InlineData(403)] + [InlineData(404)] + [InlineData(409)] + [InlineData(429)] + [InlineData(500)] + public async Task NonChallenge_Response_Should_Not_Recover( + int status) + { + _store.Replace(Token("old-token")); + + var response = new UAuthTransportResult + { + Ok = false, + Status = status + }; + + SetupResponse(response); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(response); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Reactive_Disabled_Should_Not_Recover() + { + _store.Replace(Token("old-token")); + + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateSut( + reactive: false).SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + // -------------------------------------------------------- + // Reactive recovery and replay + // -------------------------------------------------------- + + [Fact] + public async Task Challenge_Should_Replay_Once_With_New_Token() + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + SetupRotation(expected); + + var arguments = new List(); + var responses = new Queue( + new[] { Challenge(), Success() }); + + _js.Setup(x => x.InvokeAsync( + JsMethod, + It.IsAny(), + It.IsAny())) + .Returns( + (_, _, args) => + { + arguments.Add(args[0]!); + + return new ValueTask( + responses.Dequeue()); + }); + + var payload = new + { + DisplayName = "Updated" + }; + + var result = await CreateSut().SendJsonAsync( + Endpoint, + payload, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Ok.Should().BeTrue(); + + arguments.Should().HaveCount(2); + + ReadArgument(arguments[0], "accessToken") + .Should().Be("old-token"); + + ReadArgument(arguments[1], "accessToken") + .Should().Be("new-token"); + + foreach (var argument in arguments) + { + ReadArgument(argument, "url") + .Should().Be(Endpoint); + + ReadArgument(argument, "payload") + .Should().BeSameAs(payload); + } + + _recovery.Verify(x => x.RecoverAsync( + expected, + It.IsAny()), + Times.Once); + + VerifyPreparation(Times.Once()); + VerifyRequests(Times.Exactly(2)); + } + + [Fact] + public async Task Second_Challenge_Should_Not_Create_Retry_Loop() + { + _store.Replace(Token("old-token")); + + SetupRotation(_store.Capture()); + + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Exactly(2)); + } + + [Fact] + public async Task Failed_Recovery_Should_Return_Original_Response() + { + _store.Replace(Token("old-token")); + + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Same_Token_Should_Not_Be_Replayed( + bool rotateGeneration) + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + var challenge = Challenge(); + + SetupResponse(challenge); + + _recovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + if (rotateGeneration) + { + _store.TryRotate( + expected, + Token("old-token")) + .Should().BeTrue(); + } + + return _store.Capture(); + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + // -------------------------------------------------------- + // Proactive preparation + // -------------------------------------------------------- + + [Fact] + public async Task Preparation_Should_Use_Rotated_Token() + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + _recovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(() => + { + _store.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + return new UAuthRequestPreparationResult( + _store.Capture()); + }); + + object? captured = null; + + _js.Setup(x => x.InvokeAsync( + JsMethod, + It.IsAny(), + It.IsAny())) + .Callback( + (_, _, args) => captured = args[0]) + .ReturnsAsync(Success()); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Ok.Should().BeTrue(); + + captured.Should().NotBeNull(); + + ReadArgument(captured!, "accessToken") + .Should().Be("new-token"); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Theory] + [InlineData(401, 401)] + [InlineData(429, 429)] + [InlineData(503, 503)] + [InlineData(0, 401)] + public async Task Preparation_Failure_Should_Prevent_Request( + int status, + int expectedStatus) + { + _recovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(new UAuthRequestPreparationResult( + _store.Capture(), + new RefreshResult + { + IsSuccess = false, + Status = status, + RetryAfter = TimeSpan.FromSeconds(30) + })); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Ok.Should().BeFalse(); + result.Status.Should().Be(expectedStatus); + result.RetryAfter.Should().Be("30"); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Never()); + + _bootstrapper.Verify(x => x.EnsureStartedAsync( + It.IsAny()), + Times.Never); + } + + // -------------------------------------------------------- + // Authentication lifecycle + // -------------------------------------------------------- + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Authentication_Changed_During_Request_Should_Not_Recover( + bool loginAsAnotherUser) + { + _store.Replace(Token("old-token")); + + var challenge = Challenge(); + + _js.Setup(x => x.InvokeAsync( + JsMethod, + It.IsAny(), + It.IsAny())) + .Returns(() => + { + if (loginAsAnotherUser) + _store.Replace(Token("another-user-token")); + else + _store.Clear(); + + return new ValueTask( + challenge); + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Authentication_Changed_During_Recovery_Should_Not_Replay( + bool loginAsAnotherUser) + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + var challenge = Challenge(); + + SetupResponse(challenge); + + _recovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _store.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + var refreshed = _store.Capture(); + + if (loginAsAnotherUser) + _store.Replace(Token("another-user-token")); + else + _store.Clear(); + + return refreshed; + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Expired_Recovered_Token_Should_Not_Be_Replayed() + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + var challenge = Challenge(); + + SetupResponse(challenge); + + _recovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _store.TryRotate( + expected, + Token( + "expired-token", + DateTimeOffset.UtcNow.AddMinutes(-1))) + .Should().BeTrue(); + + return _store.Capture(); + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Token_Changed_During_Replay_Bootstrap_Should_Not_Send_Stale_Token() + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + SetupRotation(expected); + + var challenge = Challenge(); + + SetupResponse(challenge); + + _bootstrapper + .SetupSequence(x => x.EnsureStartedAsync( + It.IsAny())) + .Returns(Task.CompletedTask) + .Returns(() => + { + var current = _store.Capture(); + + _store.TryRotate( + current, + Token( + "expired-token", + DateTimeOffset.UtcNow.AddMinutes(-1))) + .Should().BeTrue(); + + return Task.CompletedTask; + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + // -------------------------------------------------------- + // Cancellation + // -------------------------------------------------------- + + [Fact] + public async Task Cancelled_Request_Should_Not_Prepare_Or_Send() + { + using var cts = new CancellationTokenSource(); + + cts.Cancel(); + + Func act = () => CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + cts.Token); + + await act.Should() + .ThrowAsync(); + + VerifyPreparation(Times.Never()); + VerifyRecovery(Times.Never()); + VerifyRequests(Times.Never()); + } + + [Fact] + public async Task Cancellation_During_Recovery_Should_Prevent_Replay() + { + using var cts = new CancellationTokenSource(); + + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + SetupResponse(Challenge()); + + _recovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _store.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + cts.Cancel(); + + return _store.Capture(); + }); + + Func act = () => CreateSut().SendJsonAsync( + Endpoint, + null, + UAuthRequestAuthentication.Recoverable, + cts.Token); + + await act.Should() + .ThrowAsync(); + + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Authentication_Changed_During_Replay_Bootstrap_Should_Not_Replay( + bool loginAsAnotherUser) + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + SetupRotation(expected); + + var challenge = Challenge(); + + SetupResponse(challenge); + + _bootstrapper + .SetupSequence(x => x.EnsureStartedAsync( + It.IsAny())) + .Returns(Task.CompletedTask) + .Returns(() => + { + if (loginAsAnotherUser) + { + _store.Replace(Token("another-user-token")); + } + else + { + _store.Clear(); + } + + return Task.CompletedTask; + }); + + var result = await CreateSut().SendJsonAsync( + Endpoint, + new { DisplayName = "Updated" }, + UAuthRequestAuthentication.Recoverable, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyPreparation(Times.Once()); + VerifyRecovery(Times.Once()); + VerifyRequests(Times.Once()); + + if (loginAsAnotherUser) + { + _store.Read()!.Token.Should().Be("another-user-token"); + } + else + { + _store.Read().Should().BeNull(); + } + } + +#pragma warning restore BL0016 +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshCoordinatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshCoordinatorTests.cs new file mode 100644 index 00000000..98daddd3 --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshCoordinatorTests.cs @@ -0,0 +1,319 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Tests.Unit.Helpers; +using Microsoft.Extensions.Options; +using Moq; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public class UAuthRefreshCoordinatorTests +{ + private readonly Mock _executor = new(); + private readonly InMemoryUAuthTokenStore _tokenStore = new(); + private readonly TestClock _clock = new(); + + private UAuthRefreshCoordinator CreateSut() + { + var options = Options.Create(new UAuthClientOptions()); + var schedule = new UAuthRefreshSchedule(_tokenStore, options, _clock); + + return new UAuthRefreshCoordinator(_executor.Object, _tokenStore, schedule); + } + + [Fact] + public async Task RefreshAsync_ShouldExecuteRefresh() + { + var expected = new RefreshResult + { + IsSuccess = true, + Status = 204 + }; + + var snapshot = _tokenStore.Capture(); + + _executor + .Setup(x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + snapshot)) + .ReturnsAsync(expected); + + var sut = CreateSut(); + + var result = await sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, + TestContext.Current.CancellationToken); + + result.Should().BeSameAs(expected); + + _executor.Verify( + x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + snapshot), + Times.Once); + } + + [Fact] + public async Task ConcurrentRefreshes_ShouldShareExecution() + { + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _executor + .Setup(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny())) + .Returns(completion.Task); + + var sut = CreateSut(); + var ct = TestContext.Current.CancellationToken; + + var first = sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, ct); + + var second = sut.RefreshAsync( + UAuthRefreshTrigger.Proactive, ct); + + var third = sut.RefreshAsync( + UAuthRefreshTrigger.Background, ct); + + var expected = new RefreshResult + { + IsSuccess = true, + Status = 204 + }; + + completion.SetResult(expected); + + var results = await Task.WhenAll( + first, second, third); + + results.Should().OnlyContain( + x => ReferenceEquals(x, expected)); + + _executor.Verify( + x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task CompletedRefresh_ShouldAllowNewExecution() + { + _executor + .Setup(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny())) + .ReturnsAsync(new RefreshResult + { + IsSuccess = true, + Status = 204 + }); + + var sut = CreateSut(); + var ct = TestContext.Current.CancellationToken; + + await sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, ct); + + await sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, ct); + + _executor.Verify( + x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Exactly(2)); + } + + [Fact] + public async Task CancelledWaiter_ShouldNotCancelSharedRefresh() + { + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _executor + .Setup(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny())) + .Returns(completion.Task); + + var sut = CreateSut(); + + using var cts = new CancellationTokenSource(); + + var first = sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, + cts.Token); + + var second = sut.RefreshAsync( + UAuthRefreshTrigger.Reactive, + TestContext.Current.CancellationToken); + + cts.Cancel(); + + Func wait = async () => await first; + + await wait.Should() + .ThrowAsync(); + + second.IsCompleted.Should().BeFalse(); + + completion.SetResult(new RefreshResult + { + IsSuccess = true, + Status = 204 + }); + + var result = await second; + + result.IsSuccess.Should().BeTrue(); + + _executor.Verify( + x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Reactive_Should_Not_Inherit_Recovery401_From_InFlight_Refresh() + { + var recoveryCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + var reactiveResult = new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Rotated + }; + + _executor + .Setup(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny())) + .Returns(( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot _) => + trigger == UAuthRefreshTrigger.Recovery + ? recoveryCompletion.Task + : Task.FromResult(reactiveResult)); + + var sut = CreateSut(); + var snapshot = _tokenStore.Capture(); + var ct = TestContext.Current.CancellationToken; + + var recovery = sut.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Recovery, + snapshot, + ct); + + var reactive = sut.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Reactive, + snapshot, + ct); + + recoveryCompletion.SetResult(new RefreshResult + { + IsSuccess = false, + Status = 401, + Outcome = RefreshOutcome.ReauthRequired + }); + + var recoveryResult = await recovery; + var reactiveResponse = await reactive; + + recoveryResult.Outcome.Should().Be( + RefreshOutcome.ReauthRequired); + + reactiveResponse.Should().BeSameAs(reactiveResult); + + _executor.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + snapshot), Times.Once); + } + + [Fact] + public async Task New_Generation_Should_Not_Inherit_Old_Refresh_Result() + { + _tokenStore.Replace(new AccessToken + { + Token = "initial-token", + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(10) + }); + + var original = _tokenStore.Capture(); + + var oldCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _executor + .Setup(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny())) + .Returns(( + UAuthRefreshTrigger _, + UAuthTokenSnapshot snapshot) => + { + if (snapshot.Generation == original.Generation) + return oldCompletion.Task; + + return Task.FromResult(new RefreshResult + { + IsSuccess = true, + Status = 204 + }); + }); + + var sut = CreateSut(); + var ct = TestContext.Current.CancellationToken; + + var first = sut.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Reactive, + original, + ct); + + _tokenStore.TryRotate( + original, + new AccessToken + { + Token = "rotated-token", + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(20) + }).Should().BeTrue(); + + var updated = _tokenStore.Capture(); + + updated.Epoch.Should().Be(original.Epoch); + updated.Generation.Should().Be(original.Generation + 1); + + var second = sut.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Reactive, + updated, + ct); + + oldCompletion.SetResult(new RefreshResult + { + IsSuccess = false, + ErrorCode = "stale_refresh", + Outcome = RefreshOutcome.None + }); + + await first; + + var result = await second; + + result.IsSuccess.Should().BeTrue(); + + _executor.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + updated), Times.Once); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshExecutorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshExecutorTests.cs new file mode 100644 index 00000000..2b68a628 --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshExecutorTests.cs @@ -0,0 +1,1350 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Diagnostics; +using CodeBeam.UltimateAuth.Client.Errors; +using CodeBeam.UltimateAuth.Client.Events; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Tests.Unit.Helpers; +using Microsoft.Extensions.Options; +using Moq; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public sealed class UAuthRefreshExecutorTests +{ + private readonly Mock _transport = new(); + private readonly Mock _events = new(); + private readonly InMemoryUAuthTokenStore _store = new(); + private readonly UAuthClientDiagnostics _diagnostics = new(); + private readonly TestClock _clock = new(); + + private UAuthRefreshExecutor CreateSut() + { + _events + .Setup(x => x.PublishAsync(It.IsAny())) + .Returns(Task.CompletedTask); + + _events + .Setup(x => x.PublishAsync( + It.IsAny>())) + .Returns(Task.CompletedTask); + + var options = Options.Create(new UAuthClientOptions()); + + var schedule = new UAuthRefreshSchedule( + _store, + options, + _clock); + + return new UAuthRefreshExecutor( + _transport.Object, + _events.Object, + _store, + schedule, + _diagnostics, + _clock); + } + + private AccessToken Token(string value) + { + return new AccessToken + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = _clock.UtcNow.AddMinutes(10) + }; + } + + [Fact] + public async Task Manual_refresh_tracks_manual_diagnostics() + { + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var result = await CreateSut().ExecuteAsync( + UAuthRefreshTrigger.Manual, + _store.Capture()); + + result.IsSuccess.Should().BeTrue(); + result.Outcome.Should().Be(RefreshOutcome.Touched); + + _diagnostics.ManualRefreshCount.Should().Be(1); + _diagnostics.RefreshTouchedCount.Should().Be(1); + } + + [Fact] + public async Task Recovery_401_preserves_existing_token() + { + var existing = Token("existing-token"); + _store.Replace(existing); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await CreateSut().ExecuteAsync( + UAuthRefreshTrigger.Recovery, + expected); + + result.IsSuccess.Should().BeFalse(); + result.Outcome.Should().Be( + RefreshOutcome.ReauthRequired); + + _store.Read().Should().BeSameAs(existing); + + var current = _store.Capture(); + + current.Epoch.Should().Be(expected.Epoch); + current.Generation.Should().Be(expected.Generation); + + _events.Verify( + x => x.PublishAsync( + It.IsAny()), + Times.Never); + + _events.Verify( + x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Fact] + public async Task Manual_401_clears_token_and_publishes_event() + { + _store.Replace(Token("old-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await CreateSut().ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + result.Outcome.Should().Be( + RefreshOutcome.ReauthRequired); + + var current = _store.Capture(); + + current.Token.Should().BeNull(); + current.Epoch.Should().Be(expected.Epoch + 1); + current.Generation.Should().Be(expected.Generation + 1); + + _diagnostics.RefreshReauthRequiredCount + .Should().Be(1); + + _events.Verify( + x => x.PublishAsync( + It.Is>(args => + args.Type == UAuthStateEvent.ReauthenticationRequired && + args.RefreshMode == UAuthStateEventHandlingMode.Patch && + args.Payload == current.Epoch)), + Times.Once); + } + + [Fact] + public async Task Successful_refresh_replaces_access_token() + { + var existing = Token("old-token"); + _store.Replace(existing); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "rotated", + AccessToken = "Bearer new-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = + _clock.UtcNow + .AddMinutes(10) + .ToString("O") + }); + + var result = await CreateSut().ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + result.IsSuccess.Should().BeTrue(); + + var current = _store.Capture(); + + current.Token!.Token.Should().Be("new-token"); + current.Epoch.Should().Be(expected.Epoch); + current.Generation.Should().Be(expected.Generation + 1); + + _diagnostics.RefreshRotatedCount.Should().Be(1); + } + + [Fact] + public async Task Refresh_without_new_access_token_preserves_token() + { + var existing = Token("existing-token"); + _store.Replace(existing); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "no-op" + }); + + var result = await CreateSut().ExecuteAsync( + UAuthRefreshTrigger.Background, + expected); + + result.IsSuccess.Should().BeTrue(); + + var current = _store.Capture(); + + current.Token.Should().BeSameAs(existing); + current.Epoch.Should().Be(expected.Epoch); + current.Generation.Should().Be(expected.Generation); + } + + [Fact] + public async Task Rate_limit_is_not_retried_immediately() + { + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "60" + }); + + var sut = CreateSut(); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + _store.Capture()); + + var second = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + _store.Capture()); + + first.Status.Should().Be(429); + second.Status.Should().Be(429); + second.RetryAfter.Should().NotBeNull(); + + _transport.Verify( + x => x.SendAsync( + It.IsAny()), + Times.Once); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Successful_Refresh_From_Previous_Epoch_Should_Not_Rotate_Current_Token(bool loginAsAnotherUser) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .Returns(pending.Task); + + var refresh = sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + refresh.IsCompleted.Should().BeFalse(); + + if (loginAsAnotherUser) + { + _store.Replace(Token("another-user-token")); + } + else + { + _store.Clear(); + } + + var current = _store.Capture(); + + pending.SetResult(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "rotated", + AccessToken = "Bearer stale-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = _clock.UtcNow + .AddMinutes(10) + .ToString("O") + }); + + var result = await refresh; + + result.IsSuccess.Should().BeFalse(); + result.ErrorCode.Should().Be("stale_refresh"); + result.Outcome.Should().Be(RefreshOutcome.None); + + _store.Capture().Should().Be(current); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Successful_Refresh_From_Previous_Generation_Should_Not_Overwrite_Current_Token() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .Returns(pending.Task); + + var refresh = sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + _store.TryRotate( + expected, + Token("current-token")) + .Should().BeTrue(); + + var current = _store.Capture(); + + pending.SetResult(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "rotated", + AccessToken = "Bearer stale-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = _clock.UtcNow + .AddMinutes(10) + .ToString("O") + }); + + var result = await refresh; + + result.IsSuccess.Should().BeFalse(); + result.ErrorCode.Should().Be("stale_refresh"); + + _store.Capture().Should().Be(current); + + _store.Read()!.Token.Should().Be("current-token"); + + current.Epoch.Should().Be(expected.Epoch); + + current.Generation.Should().Be( + expected.Generation + 1); + } + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual)] + [InlineData(UAuthRefreshTrigger.Reactive)] + [InlineData(UAuthRefreshTrigger.Proactive)] + [InlineData(UAuthRefreshTrigger.Background)] + [InlineData(UAuthRefreshTrigger.Recovery)] + public async Task Stale_Snapshot_Should_Not_Execute_Transport(UAuthRefreshTrigger trigger) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _store.Replace(Token("another-user-token")); + + var current = _store.Capture(); + + var result = await sut.ExecuteAsync( + trigger, + expected); + + result.IsSuccess.Should().BeFalse(); + result.ErrorCode.Should().Be("stale_refresh"); + result.Outcome.Should().Be(RefreshOutcome.None); + + _store.Capture().Should().Be(current); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Never); + } + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual)] + [InlineData(UAuthRefreshTrigger.Reactive)] + [InlineData(UAuthRefreshTrigger.Proactive)] + [InlineData(UAuthRefreshTrigger.Background)] + [InlineData(UAuthRefreshTrigger.Recovery)] + public async Task Unauthorized_From_Previous_Epoch_Should_Not_Clear_New_Authentication(UAuthRefreshTrigger trigger) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .Returns(pending.Task); + + var refresh = sut.ExecuteAsync(trigger, expected); + + _store.Replace(Token("another-user-token")); + + var current = _store.Capture(); + + pending.SetResult(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await refresh; + + result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(401); + result.ErrorCode.Should().Be("stale_refresh"); + result.Outcome.Should().Be(RefreshOutcome.None); + + _store.Capture().Should().Be(current); + + _store.Read()!.Token + .Should().Be("another-user-token"); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Fact] + public async Task Unauthorized_From_Previous_Generation_Should_Not_Clear_Rotated_Token() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .Returns(pending.Task); + + var refresh = sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + _store.TryRotate( + expected, + Token("rotated-token")) + .Should().BeTrue(); + + var current = _store.Capture(); + + pending.SetResult(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await refresh; + + result.IsSuccess.Should().BeFalse(); + result.ErrorCode.Should().Be("stale_refresh"); + + _store.Capture().Should().Be(current); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual)] + [InlineData(UAuthRefreshTrigger.Reactive)] + [InlineData(UAuthRefreshTrigger.Proactive)] + [InlineData(UAuthRefreshTrigger.Background)] + public async Task Authoritative_Unauthorized_Should_Clear_Authentication(UAuthRefreshTrigger trigger) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await sut.ExecuteAsync( + trigger, + expected); + + result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(401); + result.Outcome.Should().Be( + RefreshOutcome.ReauthRequired); + + var current = _store.Capture(); + + current.Token.Should().BeNull(); + + current.Epoch.Should().Be(expected.Epoch + 1); + + current.Generation.Should().Be( + expected.Generation + 1); + + _events.Verify(x => x.PublishAsync( + It.Is>(e => + e.Type == UAuthStateEvent.ReauthenticationRequired && + e.Payload == current.Epoch)), + Times.Once); + } + + [Fact] + public async Task Recovery_Unauthorized_Should_Preserve_Entire_Authentication_Snapshot() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 401 + }); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Recovery, + expected); + + result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(401); + result.Outcome.Should().Be( + RefreshOutcome.ReauthRequired); + + _store.Capture().Should().Be(expected); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Theory] + [InlineData(0)] + [InlineData(500)] + [InlineData(502)] + [InlineData(503)] + [InlineData(504)] + public async Task Transport_Failure_Should_Preserve_Authentication(int status) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = status + }); + + Func act = () => sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + await act.Should() + .ThrowAsync(); + + _store.Capture().Should().Be(expected); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Theory] + [InlineData(100)] + [InlineData(199)] + [InlineData(301)] + [InlineData(302)] + [InlineData(307)] + [InlineData(308)] + [InlineData(600)] + public async Task Invalid_Http_Status_Should_Preserve_Authentication(int status) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = status + }); + + Func act = () => sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + await act.Should() + .ThrowAsync(); + + _store.Capture().Should().Be(expected); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Theory] + [InlineData(400)] + [InlineData(403)] + [InlineData(404)] + [InlineData(409)] + [InlineData(422)] + public async Task Client_Error_Should_Not_Clear_Authentication(int status) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = status + }); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(status); + + _store.Capture().Should().Be(expected); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Fact] + public async Task Transport_Exception_Should_Not_Prevent_Later_Refresh() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .SetupSequence(x => x.SendAsync( + It.IsAny())) + .ThrowsAsync(new UAuthTransportException( + "Network error.")) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + Func first = () => sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + await first.Should() + .ThrowAsync(); + + _store.Capture().Should().Be(expected); + + var second = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + second.IsSuccess.Should().BeTrue(); + second.Status.Should().Be(204); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + } + + [Fact] + public async Task Rate_Limit_Should_Not_Carry_Over_To_New_Authentication_Epoch() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .SetupSequence(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "120" + }) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + first.Status.Should().Be(429); + + var throttled = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + throttled.Status.Should().Be(429); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + _store.Replace(Token("another-user-token")); + + var current = _store.Capture(); + + var second = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + current); + + second.IsSuccess.Should().BeTrue(); + + _store.Capture().Should().Be(current); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + } + + [Fact] + public async Task Rate_Limit_From_Previous_Epoch_Should_Not_Throttle_Current_Authentication() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var pending = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _transport + .SetupSequence(x => x.SendAsync( + It.IsAny())) + .Returns(pending.Task) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var refresh = sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + _store.Replace(Token("another-user-token")); + + var current = _store.Capture(); + + pending.SetResult(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "120" + }); + + var stale = await refresh; + + stale.IsSuccess.Should().BeFalse(); + stale.ErrorCode.Should().Be("stale_refresh"); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + current); + + result.IsSuccess.Should().BeTrue(); + + _store.Capture().Should().Be(current); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + } + + [Theory] + [InlineData(UAuthRefreshTrigger.Manual)] + [InlineData(UAuthRefreshTrigger.Reactive)] + [InlineData(UAuthRefreshTrigger.Proactive)] + [InlineData(UAuthRefreshTrigger.Background)] + [InlineData(UAuthRefreshTrigger.Recovery)] + public async Task All_Refresh_Triggers_Should_Respect_Existing_Throttle(UAuthRefreshTrigger trigger) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "120" + }); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + var second = await sut.ExecuteAsync( + trigger, + expected); + + first.Status.Should().Be(429); + second.Status.Should().Be(429); + + second.IsSuccess.Should().BeFalse(); + second.ErrorCode.Should().Be("rate_limited"); + + second.RetryAfter.Should().NotBeNull(); + + second.RetryAfter!.Value.Should() + .BeGreaterThan(TimeSpan.Zero); + + second.RetryAfter.Value.Should() + .BeLessThanOrEqualTo(first.RetryAfter!.Value); + + _store.Capture().Should().Be(expected); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Rate_Limit_Should_Expire_According_To_Client_Clock() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .SetupSequence(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = false, + Status = 429, + RetryAfter = "30" + }) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Manual, + expected); + + first.Status.Should().Be(429); + + _clock.Advance(TimeSpan.FromSeconds(29)); + + var throttled = await sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + throttled.Status.Should().Be(429); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + _clock.Advance(TimeSpan.FromSeconds(1)); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + expected); + + result.IsSuccess.Should().BeTrue(); + result.Status.Should().Be(204); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + } + + [Fact] + public async Task Expired_Refresh_Token_Response_Should_Preserve_Existing_Valid_Token() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "rotated", + AccessToken = "Bearer expired-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = _clock.UtcNow + .AddMinutes(-1) + .ToString("O") + }); + + Func act = () => sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + await act.Should() + .ThrowAsync(); + + _store.Capture().Should().Be(expected); + + _store.Read()!.Token.Should().Be("original-token"); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Proactive_Refresh_Without_New_Jwt_Should_Not_Immediately_Repeat(bool returnSameToken) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + var response = new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched", + AccessToken = returnSameToken + ? "Bearer original-token" + : null, + AccessTokenFormat = returnSameToken + ? "jwt" + : null, + AccessTokenHeaderFormat = returnSameToken + ? "bearer" + : null, + AccessTokenExpiresAt = returnSameToken + ? expected.Token!.ExpiresAt.ToString("O") + : null + }; + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(response); + + await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + var current = _store.Capture(); + + await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + current); + + _store.Read()!.Token.Should().Be("original-token"); + + _store.Read()!.ExpiresAt.Should().Be( + expected.Token!.ExpiresAt); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task No_Rotation_Backoff_Should_Expire_According_To_Client_Clock() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + first.IsSuccess.Should().BeTrue(); + + _clock.Advance(TimeSpan.FromSeconds(9)); + + var deferred = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + deferred.IsSuccess.Should().BeTrue(); + deferred.Outcome.Should().Be(RefreshOutcome.NoOp); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + _clock.Advance(TimeSpan.FromSeconds(1)); + + var second = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + second.IsSuccess.Should().BeTrue(); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + } + + [Theory] + [InlineData(UAuthRefreshTrigger.Proactive, 1)] + [InlineData(UAuthRefreshTrigger.Background, 1)] + [InlineData(UAuthRefreshTrigger.Manual, 2)] + [InlineData(UAuthRefreshTrigger.Reactive, 2)] + [InlineData(UAuthRefreshTrigger.Recovery, 2)] + public async Task No_Rotation_Backoff_Should_Respect_Trigger(UAuthRefreshTrigger trigger, int expectedTransportCalls) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + var result = await sut.ExecuteAsync( + trigger, + expected); + + result.IsSuccess.Should().BeTrue(); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(expectedTransportCalls)); + + _store.Capture().Should().Be(expected); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task No_Rotation_Backoff_Should_Not_Carry_Over_To_New_Credential(bool newEpoch) + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + if (newEpoch) + { + // Even the same token value must not inherit + // state from a previous authentication lifecycle. + _store.Replace(Token("original-token")); + } + else + { + _store.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + } + + var current = _store.Capture(); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + current); + + result.IsSuccess.Should().BeTrue(); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Exactly(2)); + + _store.Capture().Should().Be(current); + } + + [Fact] + public async Task Expired_Jwt_During_No_Rotation_Backoff_Should_Not_Report_Success() + { + var sut = CreateSut(); + + _store.Replace(new AccessToken + { + Token = "short-lived-token", + Format = TokenFormat.Jwt, + ExpiresAt = _clock.UtcNow.AddSeconds(5) + }); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched" + }); + + var first = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + first.IsSuccess.Should().BeTrue(); + + _clock.Advance(TimeSpan.FromSeconds(5)); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + result.IsSuccess.Should().BeFalse(); + result.Status.Should().Be(401); + + result.ErrorCode.Should().Be( + "access_token_not_rotated"); + + result.Outcome.Should().Be(RefreshOutcome.None); + + _store.Capture().Should().Be(expected); + + _transport.Verify(x => x.SendAsync( + It.IsAny()), + Times.Once); + + _events.Verify(x => x.PublishAsync( + It.IsAny>()), + Times.Never); + } + + [Fact] + public async Task Same_Jwt_Response_Should_Not_Increment_Generation() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "touched", + AccessToken = "Bearer original-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = + expected.Token!.ExpiresAt.ToString("O") + }); + + var result = await sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + result.IsSuccess.Should().BeTrue(); + + _store.Capture().Should().Be(expected); + + _store.Capture().Generation + .Should().Be(expected.Generation); + } + + [Fact] + public async Task Same_Jwt_With_Different_Expiration_Should_Be_Rejected() + { + var sut = CreateSut(); + + _store.Replace(Token("original-token")); + + var expected = _store.Capture(); + + _transport + .Setup(x => x.SendAsync( + It.IsAny())) + .ReturnsAsync(new UAuthTransportResult + { + Ok = true, + Status = 204, + RefreshOutcome = "rotated", + AccessToken = "Bearer original-token", + AccessTokenFormat = "jwt", + AccessTokenHeaderFormat = "bearer", + AccessTokenExpiresAt = + expected.Token!.ExpiresAt + .AddMinutes(10) + .ToString("O") + }); + + Func act = () => sut.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected); + + await act.Should() + .ThrowAsync(); + + _store.Capture().Should().Be(expected); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshScheduleTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshScheduleTests.cs new file mode 100644 index 00000000..579b00f7 --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRefreshScheduleTests.cs @@ -0,0 +1,1047 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Tests.Unit.Helpers; +using Microsoft.Extensions.Options; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public sealed class UAuthRefreshScheduleTests +{ + private readonly TestClock _clock = new(new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); + + private readonly InMemoryUAuthTokenStore _store = new(); + + private readonly UAuthClientAutoRefreshOptions _options = new() + { + Interval = TimeSpan.FromMinutes(5), + RefreshBeforeExpiration = TimeSpan.FromMinutes(1) + }; + + private UAuthRefreshSchedule CreateSut() + { + return new UAuthRefreshSchedule( + _store, + Options.Create(new UAuthClientOptions + { + AutoRefresh = _options + }), + _clock); + } + + private AccessToken Token( + string value, + TimeSpan lifetime, + TokenFormat format = TokenFormat.Jwt) + { + return new AccessToken + { + Token = value, + Format = format, + ExpiresAt = _clock.UtcNow + lifetime + }; + } + + private UAuthTokenSnapshot AuthenticateJwt( + UAuthRefreshSchedule sut, + TimeSpan lifetime) + { + _store.Replace(Token("jwt-token", lifetime)); + + var snapshot = _store.Capture(); + + sut.MarkAuthenticated(snapshot); + + return snapshot; + } + + private UAuthTokenSnapshot AuthenticateCookie( + UAuthRefreshSchedule sut) + { + var snapshot = _store.Capture(); + + sut.MarkAuthenticated(snapshot); + + return snapshot; + } + + // -------------------------------------------------------- + // Default configuration + // -------------------------------------------------------- + + [Fact] + public void Interval_Should_Default_To_Five_Minutes() + { + _options.Interval = null; + + var sut = CreateSut(); + + sut.Interval.Should().Be( + TimeSpan.FromMinutes(5)); + } + + [Theory] + [InlineData(10)] + [InlineData(60)] + [InlineData(300)] + [InlineData(900)] + public void Interval_Should_Use_Configured_Value( + int seconds) + { + _options.Interval = TimeSpan.FromSeconds(seconds); + + var sut = CreateSut(); + + sut.Interval.Should().Be( + TimeSpan.FromSeconds(seconds)); + } + + // -------------------------------------------------------- + // Anonymous and cookie-only authentication + // -------------------------------------------------------- + + [Fact] + public void Anonymous_Should_Not_Have_Refresh_Schedule() + { + var sut = CreateSut(); + + var snapshot = _store.Capture(); + + sut.IsAuthenticated(snapshot).Should().BeFalse(); + sut.GetNextRefreshAt(snapshot).Should().BeNull(); + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromDays(1)); + + sut.IsDue(snapshot).Should().BeFalse(); + } + + [Fact] + public void Cookie_Session_Should_Become_Due_At_Interval() + { + var sut = CreateSut(); + + var authenticatedAt = _clock.UtcNow; + + var snapshot = AuthenticateCookie(sut); + + sut.IsAuthenticated(snapshot).Should().BeTrue(); + + sut.GetNextRefreshAt(snapshot).Should().Be( + authenticatedAt.AddMinutes(5)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance( + TimeSpan.FromMinutes(5) - + TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Cookie_Session_Should_Remain_Due_Until_Refreshed() + { + var sut = CreateSut(); + + var snapshot = AuthenticateCookie(sut); + + var next = sut.GetNextRefreshAt(snapshot); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + sut.IsDue(snapshot).Should().BeTrue(); + + _clock.Advance(TimeSpan.FromHours(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.GetNextRefreshAt(snapshot).Should().Be(next); + } + + [Fact] + public void Successful_Cookie_Refresh_Should_Reset_Interval() + { + var sut = CreateSut(); + + var snapshot = AuthenticateCookie(sut); + + _clock.Advance(TimeSpan.FromMinutes(7)); + + sut.IsDue(snapshot).Should().BeTrue(); + + var refreshedAt = _clock.UtcNow; + + sut.MarkRefreshed(snapshot); + + sut.GetNextRefreshAt(snapshot).Should().Be( + refreshedAt.AddMinutes(5)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Repeated_Validation_Should_Not_Postpone_Refresh() + { + var sut = CreateSut(); + + var snapshot = AuthenticateCookie(sut); + + var originalNext = sut.GetNextRefreshAt(snapshot); + + for (var i = 0; i < 4; i++) + { + _clock.Advance(TimeSpan.FromMinutes(1)); + + sut.MarkAuthenticated(snapshot); + + sut.GetNextRefreshAt(snapshot) + .Should().Be(originalNext); + } + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromMinutes(1)); + + sut.MarkAuthenticated(snapshot); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + // -------------------------------------------------------- + // Opaque token scheduling + // -------------------------------------------------------- + + [Theory] + [InlineData(30)] + [InlineData(300)] + [InlineData(3600)] + public void Opaque_Should_Use_Interval_Not_Token_Expiration( + int lifetimeSeconds) + { + var sut = CreateSut(); + + var authenticatedAt = _clock.UtcNow; + + _store.Replace(Token( + "opaque-token", + TimeSpan.FromSeconds(lifetimeSeconds), + TokenFormat.Opaque)); + + var snapshot = _store.Capture(); + + sut.MarkAuthenticated(snapshot); + + sut.GetNextRefreshAt(snapshot).Should().Be( + authenticatedAt.AddMinutes(5)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Opaque_Without_Authentication_Should_Not_Be_Scheduled() + { + var sut = CreateSut(); + + _store.Replace(Token( + "opaque-token", + TimeSpan.FromMinutes(10), + TokenFormat.Opaque)); + + var snapshot = _store.Capture(); + + sut.IsAuthenticated(snapshot).Should().BeFalse(); + sut.GetNextRefreshAt(snapshot).Should().BeNull(); + sut.IsDue(snapshot).Should().BeFalse(); + } + + // -------------------------------------------------------- + // JWT expiration scheduling + // -------------------------------------------------------- + + [Fact] + public void Jwt_Should_Become_Due_Exactly_At_Threshold() + { + var sut = CreateSut(); + + var authenticatedAt = _clock.UtcNow; + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + sut.GetNextRefreshAt(snapshot).Should().Be( + authenticatedAt.AddMinutes(9)); + + _clock.Advance( + TimeSpan.FromMinutes(9) - + TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Theory] + [InlineData(539, false)] + [InlineData(540, true)] + [InlineData(599, true)] + [InlineData(600, true)] + [InlineData(601, true)] + public void Jwt_Should_Respect_Expiration_Threshold( + int elapsedSeconds, + bool expectedDue) + { + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _clock.Advance( + TimeSpan.FromSeconds(elapsedSeconds)); + + sut.IsDue(snapshot).Should().Be(expectedDue); + } + + [Fact] + public void Jwt_With_Zero_Threshold_Should_Refresh_At_Expiration() + { + _options.RefreshBeforeExpiration = TimeSpan.Zero; + + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + sut.GetNextRefreshAt(snapshot).Should().Be( + snapshot.Token!.ExpiresAt); + + _clock.Advance( + TimeSpan.FromMinutes(10) - + TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Theory] + [InlineData(1)] + [InlineData(5)] + [InlineData(60)] + [InlineData(3600)] + public void Jwt_Should_Not_Use_Opaque_Refresh_Interval( + int intervalSeconds) + { + _options.Interval = + TimeSpan.FromSeconds(intervalSeconds); + + var sut = CreateSut(); + + var authenticatedAt = _clock.UtcNow; + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + sut.GetNextRefreshAt(snapshot).Should().Be( + authenticatedAt.AddMinutes(9)); + } + + // -------------------------------------------------------- + // Short-lived JWT protection + // -------------------------------------------------------- + + [Theory] + [InlineData(10, 60, 5)] + [InlineData(30, 60, 15)] + [InlineData(60, 60, 30)] + [InlineData(60, 120, 30)] + [InlineData(120, 60, 60)] + [InlineData(120, 30, 90)] + [InlineData(600, 60, 540)] + public void Jwt_Threshold_Should_Be_Clamped_When_Necessary( + int lifetimeSeconds, + int thresholdSeconds, + int expectedRefreshAfterSeconds) + { + _options.RefreshBeforeExpiration = + TimeSpan.FromSeconds(thresholdSeconds); + + var sut = CreateSut(); + + var authenticatedAt = _clock.UtcNow; + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromSeconds(lifetimeSeconds)); + + sut.GetNextRefreshAt(snapshot).Should().Be( + authenticatedAt.AddSeconds( + expectedRefreshAfterSeconds)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance( + TimeSpan.FromSeconds( + expectedRefreshAfterSeconds) - + TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromTicks(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Short_Lived_Jwt_Should_Not_Immediately_Refresh_After_Rotation() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromSeconds(30)); + + _clock.Advance(TimeSpan.FromSeconds(15)); + + sut.IsDue(original).Should().BeTrue(); + + var refreshedAt = _clock.UtcNow; + + _store.TryRotate( + original, + Token( + "rotated-token", + TimeSpan.FromSeconds(30))) + .Should().BeTrue(); + + sut.MarkRefreshed(original); + + var rotated = _store.Capture(); + + sut.GetNextRefreshAt(rotated).Should().Be( + refreshedAt.AddSeconds(15)); + + sut.IsDue(rotated).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromSeconds(14)); + + sut.IsDue(rotated).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromSeconds(1)); + + sut.IsDue(rotated).Should().BeTrue(); + } + + [Fact] + public void Repeated_Short_Lived_Rotations_Should_Not_Create_Refresh_Storm() + { + var sut = CreateSut(); + + var current = AuthenticateJwt( + sut, + TimeSpan.FromSeconds(30)); + + var initialEpoch = current.Epoch; + var initialGeneration = current.Generation; + + for (var i = 0; i < 20; i++) + { + sut.IsDue(current).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromSeconds(15)); + + sut.IsDue(current).Should().BeTrue(); + + _store.TryRotate( + current, + Token( + $"rotated-token-{i}", + TimeSpan.FromSeconds(30))) + .Should().BeTrue(); + + sut.MarkRefreshed(current); + + current = _store.Capture(); + + sut.IsDue(current).Should().BeFalse(); + + sut.GetNextRefreshAt(current).Should().Be( + _clock.UtcNow.AddSeconds(15)); + } + + current.Epoch.Should().Be(initialEpoch); + + current.Generation.Should().Be( + initialGeneration + 20); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(-60)] + public void Already_Expired_Jwt_Should_Be_Due_Immediately( + int lifetimeSeconds) + { + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromSeconds(lifetimeSeconds)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.GetNextRefreshAt(snapshot).Should().Be( + snapshot.Token!.ExpiresAt); + } + + // -------------------------------------------------------- + // Successful refresh and rotation + // -------------------------------------------------------- + + [Fact] + public void Jwt_Rotation_Should_Recalculate_Next_Refresh() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + sut.IsDue(original).Should().BeTrue(); + + var refreshedAt = _clock.UtcNow; + + _store.TryRotate( + original, + Token( + "rotated-token", + TimeSpan.FromMinutes(20))) + .Should().BeTrue(); + + sut.MarkRefreshed(original); + + var rotated = _store.Capture(); + + sut.GetNextRefreshAt(rotated).Should().Be( + refreshedAt.AddMinutes(19)); + + sut.IsDue(rotated).Should().BeFalse(); + + sut.IsAuthenticated(rotated).Should().BeTrue(); + } + + [Fact] + public void Refresh_Without_Token_Rotation_Should_Not_Extend_Jwt_Expiration() + { + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.MarkRefreshed(snapshot); + + _clock.Advance(TimeSpan.FromMinutes(1)); + + sut.IsDue(snapshot).Should().BeTrue(); + + _store.Capture().Should().Be(snapshot); + + _store.Read()!.ExpiresAt.Should().Be( + _clock.UtcNow); + } + + // -------------------------------------------------------- + // Authentication lifecycle + // -------------------------------------------------------- + + [Fact] + public void Logout_Should_Remove_Cookie_Refresh_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _store.Clear(); + + sut.MarkUnauthenticated(original.Epoch); + + var current = _store.Capture(); + + sut.IsAuthenticated(current).Should().BeFalse(); + sut.GetNextRefreshAt(current).Should().BeNull(); + sut.IsDue(current).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromHours(1)); + + sut.IsDue(current).Should().BeFalse(); + } + + [Fact] + public void Logout_Should_Remove_Jwt_Refresh_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _store.Clear(); + + sut.MarkUnauthenticated(original.Epoch); + + var current = _store.Capture(); + + sut.IsAuthenticated(current).Should().BeFalse(); + sut.GetNextRefreshAt(current).Should().BeNull(); + sut.IsDue(current).Should().BeFalse(); + } + + [Fact] + public void Unconditional_Clear_Should_Reset_Schedule() + { + var sut = CreateSut(); + + var snapshot = AuthenticateCookie(sut); + + sut.MarkUnauthenticated(); + + sut.IsAuthenticated(snapshot).Should().BeFalse(); + sut.GetNextRefreshAt(snapshot).Should().BeNull(); + sut.IsDue(snapshot).Should().BeFalse(); + } + + [Fact] + public void New_Authentication_Should_Start_New_Interval() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _clock.Advance(TimeSpan.FromMinutes(4)); + + _store.Clear(); + + var current = _store.Capture(); + + sut.MarkAuthenticated(current); + + current.Epoch.Should().NotBe(original.Epoch); + + sut.GetNextRefreshAt(current).Should().Be( + _clock.UtcNow.AddMinutes(5)); + + _clock.Advance(TimeSpan.FromMinutes(1)); + + sut.IsDue(current).Should().BeFalse(); + + _clock.Advance(TimeSpan.FromMinutes(4)); + + sut.IsDue(current).Should().BeTrue(); + } + + [Fact] + public void Stale_Authentication_Event_Should_Not_Restore_Old_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _store.Clear(); + + sut.MarkUnauthenticated(original.Epoch); + + sut.MarkAuthenticated(original); + + var current = _store.Capture(); + + sut.IsAuthenticated(original).Should().BeFalse(); + sut.IsAuthenticated(current).Should().BeFalse(); + sut.GetNextRefreshAt(current).Should().BeNull(); + } + + [Fact] + public void Stale_Logout_Should_Not_Clear_New_Authentication_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _store.Clear(); + + var current = _store.Capture(); + + sut.MarkAuthenticated(current); + + var next = sut.GetNextRefreshAt(current); + + sut.MarkUnauthenticated(original.Epoch); + + sut.IsAuthenticated(current).Should().BeTrue(); + + sut.GetNextRefreshAt(current).Should().Be(next); + } + + [Fact] + public void Stale_Refresh_Should_Not_Postpone_New_Authentication_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _clock.Advance(TimeSpan.FromMinutes(1)); + + _store.Clear(); + + var current = _store.Capture(); + + sut.MarkAuthenticated(current); + + var next = sut.GetNextRefreshAt(current); + + _clock.Advance(TimeSpan.FromMinutes(2)); + + sut.MarkRefreshed(original); + + sut.GetNextRefreshAt(current).Should().Be(next); + + sut.IsAuthenticated(current).Should().BeTrue(); + } + + [Fact] + public void Refresh_Should_Not_Authenticate_Anonymous_Cookie_State() + { + var sut = CreateSut(); + + var snapshot = _store.Capture(); + + sut.MarkRefreshed(snapshot); + + sut.IsAuthenticated(snapshot).Should().BeFalse(); + sut.GetNextRefreshAt(snapshot).Should().BeNull(); + sut.IsDue(snapshot).Should().BeFalse(); + } + + [Fact] + public void Previous_Epoch_Should_Not_Control_Current_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateCookie(sut); + + _store.Clear(); + + var current = _store.Capture(); + + sut.IsAuthenticated(current).Should().BeFalse(); + sut.GetNextRefreshAt(current).Should().BeNull(); + sut.IsDue(current).Should().BeFalse(); + + sut.MarkAuthenticated(current); + + sut.IsAuthenticated(original).Should().BeFalse(); + sut.IsAuthenticated(current).Should().BeTrue(); + } + + [Fact] + public void Short_Lived_Jwt_Before_Initial_Validation_Should_Not_Immediately_Refresh() + { + _options.RefreshBeforeExpiration = + TimeSpan.FromMinutes(1); + + var sut = CreateSut(); + + _store.Replace(Token( + "short-lived-token", + TimeSpan.FromSeconds(30))); + + var snapshot = _store.Capture(); + + sut.IsAuthenticated(snapshot).Should().BeFalse(); + + sut.IsDue(snapshot).Should().BeFalse(); + } + + [Fact] + public void Stale_Jwt_Snapshot_Should_Not_Be_Eligible_For_Refresh() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + sut.IsDue(original).Should().BeTrue(); + + _store.Clear(); + + sut.MarkUnauthenticated(original.Epoch); + + sut.GetNextRefreshAt(original).Should().BeNull(); + + sut.IsDue(original).Should().BeFalse(); + } + + [Fact] + public void Jwt_Refresh_Without_Rotation_Should_Not_Postpone_Refresh_Due_Time() + { + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + var originalNext = sut.GetNextRefreshAt(snapshot); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.MarkRefreshed(snapshot); + + sut.GetNextRefreshAt(snapshot).Should().Be(originalNext); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Initial_Validation_Should_Not_Postpone_Existing_Jwt_Schedule() + { + var sut = CreateSut(); + + var observedAt = _clock.UtcNow; + + _store.Replace(Token("short-lived-token", TimeSpan.FromSeconds(30))); + + var snapshot = _store.Capture(); + + var next = sut.GetNextRefreshAt(snapshot); + + next.Should().Be(observedAt.AddSeconds(15)); + + _clock.Advance(TimeSpan.FromSeconds(10)); + + sut.MarkAuthenticated(snapshot); + + sut.IsAuthenticated(snapshot).Should().BeTrue(); + + sut.GetNextRefreshAt(snapshot).Should().Be(next); + + _clock.Advance(TimeSpan.FromSeconds(5)); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Fact] + public void Same_Jwt_In_New_Generation_Should_Preserve_Refresh_Schedule() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + var next = sut.GetNextRefreshAt(original); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + _store.TryRotate( + original, + original.Token!) + .Should().BeTrue(); + + sut.MarkRefreshed(original); + + var current = _store.Capture(); + + current.Generation.Should().Be( + original.Generation + 1); + + sut.GetNextRefreshAt(current).Should().Be(next); + + sut.IsDue(current).Should().BeTrue(); + } + + [Fact] + public void Stale_Jwt_Generation_Should_Not_Be_Eligible_For_Refresh() + { + var sut = CreateSut(); + + var original = AuthenticateJwt( + sut, + TimeSpan.FromMinutes(10)); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + sut.IsDue(original).Should().BeTrue(); + + _store.TryRotate( + original, + Token( + "rotated-token", + TimeSpan.FromMinutes(10))) + .Should().BeTrue(); + + sut.MarkRefreshed(original); + + var current = _store.Capture(); + + current.Epoch.Should().Be(original.Epoch); + + sut.GetNextRefreshAt(original).Should().BeNull(); + sut.IsDue(original).Should().BeFalse(); + + sut.GetNextRefreshAt(current).Should().Be( + _clock.UtcNow.AddMinutes(9)); + + sut.IsDue(current).Should().BeFalse(); + } + + [Fact] + public void Repeated_Jwt_Schedule_Queries_Should_Not_Postpone_Refresh() + { + var sut = CreateSut(); + + _store.Replace(Token( + "short-lived-token", + TimeSpan.FromSeconds(30))); + + var snapshot = _store.Capture(); + + var next = sut.GetNextRefreshAt(snapshot); + + for (var i = 0; i < 14; i++) + { + _clock.Advance(TimeSpan.FromSeconds(1)); + + sut.GetNextRefreshAt(snapshot).Should().Be(next); + + sut.IsDue(snapshot).Should().BeFalse(); + } + + _clock.Advance(TimeSpan.FromSeconds(1)); + + sut.GetNextRefreshAt(snapshot).Should().Be(next); + + sut.IsDue(snapshot).Should().BeTrue(); + } + + [Theory] + [InlineData(60)] + [InlineData(300)] + [InlineData(900)] + public void Jwt_Retry_Should_Not_Use_Opaque_Interval(int intervalSeconds) + { + _options.Interval = TimeSpan.FromSeconds(intervalSeconds); + + var sut = CreateSut(); + + var snapshot = AuthenticateJwt(sut, TimeSpan.FromSeconds(30)); + + _clock.Advance(TimeSpan.FromSeconds(15)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.GetRetryAt(snapshot).Should().Be(_clock.UtcNow.AddSeconds(10)); + } + + [Theory] + [InlineData(30)] + [InlineData(60)] + [InlineData(300)] + [InlineData(900)] + public void Cookie_Retry_Should_Use_Configured_Interval(int intervalSeconds) + { + _options.Interval = + TimeSpan.FromSeconds(intervalSeconds); + + var sut = CreateSut(); + + var snapshot = AuthenticateCookie(sut); + + _clock.Advance( + TimeSpan.FromSeconds(intervalSeconds)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.GetRetryAt(snapshot).Should().Be( + _clock.UtcNow.AddSeconds(intervalSeconds)); + } + + [Fact] + public void Opaque_Retry_Should_Use_Configured_Interval() + { + var sut = CreateSut(); + + _store.Replace(Token( + "opaque-token", + TimeSpan.FromHours(1), + TokenFormat.Opaque)); + + var snapshot = _store.Capture(); + + sut.MarkAuthenticated(snapshot); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + sut.IsDue(snapshot).Should().BeTrue(); + + sut.GetRetryAt(snapshot).Should().Be( + _clock.UtcNow.AddMinutes(5)); + } + + [Fact] + public void Jwt_Retry_Should_Not_Modify_Expiration_Schedule() + { + var sut = CreateSut(); + + var snapshot = AuthenticateJwt( + sut, + TimeSpan.FromSeconds(30)); + + var originalNext = + sut.GetNextRefreshAt(snapshot); + + _clock.Advance(TimeSpan.FromSeconds(15)); + + var retryAt = sut.GetRetryAt(snapshot); + + retryAt.Should().Be( + _clock.UtcNow.AddSeconds(10)); + + sut.GetNextRefreshAt(snapshot) + .Should().Be(originalNext); + + sut.IsDue(snapshot).Should().BeTrue(); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRequestRecoveryTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRequestRecoveryTests.cs new file mode 100644 index 00000000..168f232d --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthRequestRecoveryTests.cs @@ -0,0 +1,1095 @@ +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; +using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Options; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Tests.Unit.Helpers; +using Microsoft.Extensions.Options; +using Moq; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Client; + +public sealed class UAuthRequestRecoveryTests +{ + private readonly TestClock _clock = new(new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); + + private readonly InMemoryUAuthTokenStore _store = new(); + + private readonly Mock _coordinator = new(); + + private readonly UAuthClientAutoRefreshOptions _autoRefresh = new() + { + Reactive = true, + Proactive = true, + Interval = TimeSpan.FromMinutes(5), + RefreshBeforeExpiration = TimeSpan.FromMinutes(1) + }; + + private readonly UAuthRefreshSchedule _schedule; + + public UAuthRequestRecoveryTests() + { + _schedule = new UAuthRefreshSchedule( + _store, + CreateOptions(), + _clock); + } + + private IOptions CreateOptions() + { + return Options.Create(new UAuthClientOptions + { + AutoRefresh = _autoRefresh + }); + } + + private UAuthRequestRecovery CreateSut() + { + return new UAuthRequestRecovery( + _store, + _coordinator.Object, + _schedule, + CreateOptions(), + _clock); + } + + private AccessToken Token( + string value, + TimeSpan? lifetime = null) + { + return new AccessToken + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = _clock.UtcNow + + (lifetime ?? TimeSpan.FromMinutes(10)) + }; + } + + private UAuthTokenSnapshot Authenticate( + TimeSpan? lifetime = null) + { + _store.Replace(Token("original-token", lifetime)); + + var snapshot = _store.Capture(); + + _schedule.MarkAuthenticated(snapshot); + + return snapshot; + } + + private UAuthTokenSnapshot AuthenticateDue() + { + var snapshot = Authenticate(); + + _clock.Advance(TimeSpan.FromMinutes(9)); + + _schedule.IsDue(snapshot).Should().BeTrue(); + + return snapshot; + } + + private UAuthTokenSnapshot Rotate( + UAuthTokenSnapshot expected, + string value = "rotated-token", + TimeSpan? lifetime = null) + { + _store.TryRotate( + expected, + Token(value, lifetime)) + .Should().BeTrue(); + + return _store.Capture(); + } + + private static RefreshResult Success() + { + return new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Rotated + }; + } + + private static RefreshResult Failure( + int status, + string? errorCode = null, + RefreshOutcome outcome = RefreshOutcome.None) + { + return new RefreshResult + { + IsSuccess = false, + Status = status, + ErrorCode = errorCode, + Outcome = outcome + }; + } + + private void SetupRefresh( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot expected, + Func result) + { + _coordinator + .Setup(x => x.RefreshIfCurrentAsync( + trigger, + expected, + It.IsAny())) + .ReturnsAsync(result); + } + + private void VerifyRefresh( + UAuthRefreshTrigger trigger, + UAuthTokenSnapshot expected, + Times times) + { + _coordinator.Verify(x => x.RefreshIfCurrentAsync( + trigger, + expected, + It.IsAny()), + times); + } + + private void VerifyNoRefresh() + { + _coordinator.Verify(x => x.RefreshIfCurrentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + } + + // -------------------------------------------------------- + // Proactive refresh + // -------------------------------------------------------- + + [Fact] + public async Task Prepare_Should_Not_Refresh_When_Proactive_Disabled() + { + var expected = AuthenticateDue(); + + _autoRefresh.Proactive = false; + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Should().Be(expected); + result.Failure.Should().BeNull(); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Prepare_Should_Not_Refresh_When_Not_Authenticated() + { + var expected = _store.Capture(); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Should().Be(expected); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Prepare_Should_Not_Refresh_Before_Threshold() + { + var expected = Authenticate(); + + _clock.Advance( + TimeSpan.FromMinutes(9) - + TimeSpan.FromMilliseconds(1)); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Should().Be(expected); + + VerifyNoRefresh(); + } + + [Theory] + [InlineData(540)] + [InlineData(600)] + [InlineData(660)] + public async Task Prepare_Should_Refresh_At_Threshold_Or_After( + int elapsedSeconds) + { + var expected = Authenticate(); + + _clock.Advance( + TimeSpan.FromSeconds(elapsedSeconds)); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + Rotate(expected); + + return Success(); + }); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Failure.Should().BeNull(); + + result.Snapshot.Token!.Token + .Should().Be("rotated-token"); + + result.Snapshot.Epoch + .Should().Be(expected.Epoch); + + result.Snapshot.Generation + .Should().Be(expected.Generation + 1); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Prepare_Should_Proceed_When_Refresh_No_Longer_Due() + { + var expected = AuthenticateDue(); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => Failure(0, "refresh_not_due")); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Should().Be(expected); + result.Failure.Should().BeNull(); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Prepare_Should_Use_Latest_Token_When_Already_Rotated() + { + var expected = AuthenticateDue(); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + Rotate(expected); + + return Failure(0, "token_changed"); + }); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Should().Be(_store.Capture()); + + result.Snapshot.Token!.Token + .Should().Be("rotated-token"); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Theory] + [InlineData(400)] + [InlineData(403)] + [InlineData(409)] + [InlineData(500)] + [InlineData(503)] + public async Task Prepare_Should_Block_Request_When_Refresh_Fails( + int status) + { + var expected = AuthenticateDue(); + + var failure = Failure(status); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => failure); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeFalse(); + result.Failure.Should().BeSameAs(failure); + + _store.Capture().Should().Be(expected); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Prepare_Should_Block_Request_When_Reauthentication_Required() + { + var expected = AuthenticateDue(); + + var failure = Failure( + 401, + outcome: RefreshOutcome.ReauthRequired); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + _store.TryClear(expected) + .Should().BeTrue(); + + return failure; + }); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeFalse(); + result.Failure.Should().BeSameAs(failure); + result.Snapshot.Token.Should().BeNull(); + + result.Snapshot.Epoch + .Should().Be(expected.Epoch + 1); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + // -------------------------------------------------------- + // Proactive rate limiting + // -------------------------------------------------------- + + [Theory] + [InlineData(540, true)] + [InlineData(599, true)] + [InlineData(600, false)] + [InlineData(601, false)] + public async Task Prepare_429_Should_Proceed_Only_With_Valid_Token( + int elapsedSeconds, + bool canProceed) + { + var expected = Authenticate(); + + _clock.Advance( + TimeSpan.FromSeconds(elapsedSeconds)); + + var throttle = new RefreshResult + { + IsSuccess = false, + Status = 429, + ErrorCode = "rate_limited", + RetryAfter = TimeSpan.FromSeconds(30) + }; + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => throttle); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().Be(canProceed); + + if (canProceed) + { + result.Failure.Should().BeNull(); + } + else + { + result.Failure.Should().BeSameAs(throttle); + } + + _store.Capture().Should().Be(expected); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Prepare_429_Should_Allow_Authenticated_Cookie_Only_Request() + { + var expected = _store.Capture(); + + _schedule.MarkAuthenticated(expected); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + _schedule.IsDue(expected).Should().BeTrue(); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => Failure(429, "rate_limited")); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeTrue(); + result.Snapshot.Token.Should().BeNull(); + result.Failure.Should().BeNull(); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Prepare_429_Should_Block_When_Cookie_State_Is_No_Longer_Authenticated() + { + var expected = _store.Capture(); + + _schedule.MarkAuthenticated(expected); + + _clock.Advance(TimeSpan.FromMinutes(5)); + + var throttle = Failure(429, "rate_limited"); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + _schedule.MarkUnauthenticated(); + + return throttle; + }); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeFalse(); + result.Failure.Should().BeSameAs(throttle); + } + + // -------------------------------------------------------- + // Reactive refresh + // -------------------------------------------------------- + + [Fact] + public async Task Recover_Should_Not_Refresh_When_Reactive_Disabled() + { + var expected = Authenticate(); + + _autoRefresh.Reactive = false; + + var result = await CreateSut().RecoverAsync( + expected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Recover_Should_Not_Replay_Cookie_Only_Request() + { + var expected = _store.Capture(); + + _schedule.MarkAuthenticated(expected); + + var result = await CreateSut().RecoverAsync( + expected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Recover_Should_Return_New_Token_After_Successful_Refresh() + { + var expected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + expected, + () => + { + Rotate(expected); + + return Success(); + }); + + var result = await CreateSut().RecoverAsync( + expected, + TestContext.Current.CancellationToken); + + result.Should().NotBeNull(); + result.Should().Be(_store.Capture()); + + result!.Token!.Token + .Should().Be("rotated-token"); + + result.Epoch.Should().Be(expected.Epoch); + + result.Generation + .Should().Be(expected.Generation + 1); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Late_401_Should_Reuse_Already_Rotated_Token_Without_Refresh() + { + var rejected = Authenticate(); + + var rotated = Rotate(rejected); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().Be(rotated); + + VerifyNoRefresh(); + } + + [Theory] + [InlineData("original-token", 600)] + [InlineData("rotated-token", 0)] + [InlineData("rotated-token", -60)] + public async Task Late_401_Should_Not_Reuse_Invalid_Rotation( + string token, + int lifetimeSeconds) + { + var rejected = Authenticate(); + + Rotate( + rejected, + token, + TimeSpan.FromSeconds(lifetimeSeconds)); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + VerifyNoRefresh(); + } + + [Theory] + [InlineData(400)] + [InlineData(401)] + [InlineData(403)] + [InlineData(409)] + [InlineData(429)] + [InlineData(500)] + [InlineData(503)] + public async Task Recover_Should_Not_Replay_When_Refresh_Fails( + int status) + { + var rejected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + () => Failure(status)); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + [Fact] + public async Task Recover_Should_Not_Replay_When_Success_Does_Not_Rotate_Token() + { + var rejected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Success); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + _store.Capture().Should().Be(rejected); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + [Theory] + [InlineData("original-token", 600)] + [InlineData("rotated-token", 0)] + [InlineData("rotated-token", -60)] + public async Task Recover_Should_Not_Replay_When_Rotated_Token_Is_Invalid( + string token, + int lifetimeSeconds) + { + var rejected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + () => + { + Rotate( + rejected, + token, + TimeSpan.FromSeconds(lifetimeSeconds)); + + return Success(); + }); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + [Fact] + public async Task Recover_Should_Use_Concurrent_Rotation_When_Coordinator_Returns_TokenChanged() + { + var rejected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + () => + { + Rotate(rejected); + + return Failure(0, "token_changed"); + }); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().Be(_store.Capture()); + + result!.Token!.Token + .Should().Be("rotated-token"); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + // -------------------------------------------------------- + // Authentication lifecycle + // -------------------------------------------------------- + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Recover_Should_Reject_Previous_Authentication_Epoch( + bool loginAsAnotherUser) + { + var rejected = Authenticate(); + + if (loginAsAnotherUser) + { + _store.Replace(Token("another-user-token")); + } + else + { + _store.Clear(); + } + + var current = _store.Capture(); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + _store.Capture().Should().Be(current); + + VerifyNoRefresh(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Recover_Should_Not_Replay_When_Epoch_Changes_During_Refresh( + bool loginAsAnotherUser) + { + var rejected = Authenticate(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + () => + { + if (loginAsAnotherUser) + { + _store.Replace(Token("another-user-token")); + } + else + { + _store.Clear(); + } + + return Success(); + }); + + var result = await CreateSut().RecoverAsync( + rejected, + TestContext.Current.CancellationToken); + + result.Should().BeNull(); + + _store.Capture().Epoch + .Should().Be(rejected.Epoch + 1); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Prepare_Should_Block_Request_When_Epoch_Changes_During_Refresh( + bool loginAsAnotherUser) + { + var expected = AuthenticateDue(); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + if (loginAsAnotherUser) + { + _store.Replace(Token("another-user-token")); + } + else + { + _store.Clear(); + } + + return Success(); + }); + + var result = await CreateSut().PrepareAsync( + TestContext.Current.CancellationToken); + + result.CanProceed.Should().BeFalse(); + result.Failure.Should().NotBeNull(); + result.Failure!.Status.Should().Be(401); + + result.Failure.ErrorCode + .Should().Be("authentication_changed"); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + // -------------------------------------------------------- + // Cancellation + // -------------------------------------------------------- + + [Fact] + public async Task Prepare_Should_Honor_PreCancelled_Token() + { + AuthenticateDue(); + + using var cts = new CancellationTokenSource(); + + cts.Cancel(); + + Func act = () => + CreateSut().PrepareAsync(cts.Token); + + await act.Should() + .ThrowAsync(); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Recover_Should_Honor_PreCancelled_Token() + { + var rejected = Authenticate(); + + using var cts = new CancellationTokenSource(); + + cts.Cancel(); + + Func act = () => + CreateSut().RecoverAsync(rejected, cts.Token); + + await act.Should() + .ThrowAsync(); + + VerifyNoRefresh(); + } + + [Fact] + public async Task Prepare_Should_Honor_Cancellation_During_Refresh() + { + var expected = AuthenticateDue(); + + using var cts = new CancellationTokenSource(); + + SetupRefresh( + UAuthRefreshTrigger.Proactive, + expected, + () => + { + Rotate(expected); + + cts.Cancel(); + + return Success(); + }); + + Func act = () => + CreateSut().PrepareAsync(cts.Token); + + await act.Should() + .ThrowAsync(); + + // Cancellation of a request must not undo a + // successfully completed shared token rotation. + _store.Read()!.Token + .Should().Be("rotated-token"); + + VerifyRefresh( + UAuthRefreshTrigger.Proactive, + expected, + Times.Once()); + } + + [Fact] + public async Task Recover_Should_Honor_Cancellation_During_Refresh() + { + var rejected = Authenticate(); + + using var cts = new CancellationTokenSource(); + + SetupRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + () => + { + Rotate(rejected); + + cts.Cancel(); + + return Success(); + }); + + Func act = () => + CreateSut().RecoverAsync(rejected, cts.Token); + + await act.Should() + .ThrowAsync(); + + _store.Read()!.Token + .Should().Be("rotated-token"); + + VerifyRefresh( + UAuthRefreshTrigger.Reactive, + rejected, + Times.Once()); + } + + [Fact] + public async Task Concurrent_Recoveries_Should_Share_One_Refresh() + { + var rejected = Authenticate(); + + var executor = new Mock(); + + var pendingRefresh = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + executor + .Setup(x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + rejected)) + .Returns(pendingRefresh.Task); + + var coordinator = new UAuthRefreshCoordinator( + executor.Object, + _store, + _schedule); + + var sut = new UAuthRequestRecovery( + _store, + coordinator, + _schedule, + CreateOptions(), + _clock); + + var ct = TestContext.Current.CancellationToken; + + var requests = Enumerable.Range(0, 20) + .Select(_ => sut.RecoverAsync(rejected, ct)) + .ToArray(); + + requests.All(x => !x.IsCompleted) + .Should().BeTrue(); + + executor.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Reactive, + rejected), + Times.Once); + + var rotated = Rotate(rejected); + + pendingRefresh.SetResult(Success()); + + var results = await Task.WhenAll(requests); + + foreach (var result in results) + { + result.Should().Be(rotated); + } + + executor.Verify(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + + // A late response for the original token must not + // cause another refresh after the flight completed. + var lateResult = await sut.RecoverAsync(rejected, ct); + + lateResult.Should().Be(rotated); + + executor.Verify(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Proactive_Reactive_And_Background_Should_Share_One_Refresh() + { + var expected = AuthenticateDue(); + + var executor = new Mock(); + + var pendingRefresh = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + executor + .Setup(x => x.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected)) + .Returns(pendingRefresh.Task); + + var coordinator = new UAuthRefreshCoordinator( + executor.Object, + _store, + _schedule); + + var sut = new UAuthRequestRecovery( + _store, + coordinator, + _schedule, + CreateOptions(), + _clock); + + var ct = TestContext.Current.CancellationToken; + + var proactive = sut.PrepareAsync(ct); + + var reactive = sut.RecoverAsync(expected, ct); + + var background = coordinator.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Background, + expected, + ct); + + proactive.IsCompleted.Should().BeFalse(); + reactive.IsCompleted.Should().BeFalse(); + background.IsCompleted.Should().BeFalse(); + + executor.Verify(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + + var rotated = Rotate(expected); + + _schedule.MarkRefreshed(expected); + + pendingRefresh.SetResult(Success()); + + var preparation = await proactive; + var recovered = await reactive; + var backgroundResult = await background; + + preparation.CanProceed.Should().BeTrue(); + preparation.Snapshot.Should().Be(rotated); + + recovered.Should().Be(rotated); + + backgroundResult.IsSuccess.Should().BeTrue(); + + _schedule.IsDue(rotated).Should().BeFalse(); + + executor.Verify(x => x.ExecuteAsync( + UAuthRefreshTrigger.Proactive, + expected), + Times.Once); + + executor.Verify(x => x.ExecuteAsync( + It.IsAny(), + It.IsAny()), + Times.Once); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceClientTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceClientTests.cs index e9680496..b4724f2b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceClientTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceClientTests.cs @@ -1,6 +1,6 @@ using AwesomeAssertions; -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Services; using Moq; @@ -10,8 +10,7 @@ public class UAuthResourceClientTests { private readonly Mock _transport = new(); - private UAuthResourceClient CreateClient() - => new(_transport.Object); + private UAuthResourceClient CreateClient() => new(_transport.Object); [Theory] [InlineData("GET")] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceRequestClientTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceRequestClientTests.cs index ad60b22b..b240a889 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceRequestClientTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResourceRequestClientTests.cs @@ -1,11 +1,11 @@ using AwesomeAssertions; using CodeBeam.UltimateAuth.Client; +using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Blazor.Infrastructure; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; -using Microsoft.AspNetCore.Components; +using CodeBeam.UltimateAuth.Core.Contracts; using Microsoft.Extensions.Options; using Microsoft.JSInterop; using Moq; @@ -14,13 +14,43 @@ namespace CodeBeam.UltimateAuth.Tests.Unit; public class UAuthResourceRequestClientTests { + +#pragma warning disable BL0016 + private readonly Mock _js = new(); private readonly Mock _bootstrapper = new(); + private readonly Mock _requestRecovery = new(); + private readonly InMemoryUAuthTokenStore _tokenStore = new(); + + private const string ResourceEndpoint = "/api/products"; + private const string ResourceRequest = "uauth.resourceRequest"; + + public UAuthResourceRequestClientTests() + { + _bootstrapper + .Setup(x => x.EnsureStartedAsync( + It.IsAny())) + .Returns(Task.CompletedTask); + + _requestRecovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(() => + new UAuthRequestPreparationResult( + _tokenStore.Capture())); + + _requestRecovery + .Setup(x => x.RecoverAsync( + It.IsAny(), + It.IsAny())) + .ReturnsAsync((UAuthTokenSnapshot?)null); + } private UAuthResourceRequestClient CreateClient( string? baseAddress = "https://localhost:6120", UAuthResourceCredentialsMode credentials = - UAuthResourceCredentialsMode.Auto) + UAuthResourceCredentialsMode.Auto, + bool reactive = true) { var options = Options.Create(new UAuthClientOptions { @@ -28,63 +58,118 @@ private UAuthResourceRequestClient CreateClient( { BaseAddress = baseAddress, Credentials = credentials + }, + AutoRefresh = new UAuthClientAutoRefreshOptions + { + Reactive = reactive } }); return new UAuthResourceRequestClient( _js.Object, _bootstrapper.Object, - new InMemoryUAuthTokenStore(), + _tokenStore, + _requestRecovery.Object, options); } + private static AccessToken Token(string value) + => new() + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(10) + }; + + private static UAuthResourceTransportResult Success( + int status = 200) + => new() + { + Ok = true, + Status = status + }; + + private static UAuthResourceTransportResult Challenge() + => new() + { + Ok = false, + Status = 401, + AuthRecovery = "challenge" + }; + private void SetupResponse( UAuthResourceTransportResult? response) { _js.Setup(x => x.InvokeAsync( - "uauth.resourceRequest", + ResourceRequest, It.IsAny(), It.IsAny())) .ReturnsAsync(response!); } + private void VerifyRequests(Times times) + { + _js.Verify(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny()), + times); + } + + private void VerifyRecovery(Times times) + { + _requestRecovery.Verify(x => x.RecoverAsync( + It.IsAny(), + It.IsAny()), + times); + } + + private static T? ReadArgument( + object options, + string name) + { + return (T?)options.GetType() + .GetProperty(name)! + .GetValue(options); + } + + // ------------------------------------------------------------ + // Bootstrap and transport + // ------------------------------------------------------------ + [Fact] public async Task Send_Should_Ensure_Bootstrap_Before_JS_Request() { - var bootstrapCompleted = - new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var bootstrapCompleted = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); _bootstrapper .Setup(x => x.EnsureStartedAsync( It.IsAny())) .Returns(bootstrapCompleted.Task); - SetupResponse(new UAuthResourceTransportResult - { - Ok = true, - Status = 200 - }); + SetupResponse(Success()); var client = CreateClient(); - var task = client.SendAsync("GET", "/api/products", ct: TestContext.Current.CancellationToken); + var task = client.SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); _bootstrapper.Verify(x => x.EnsureStartedAsync( - It.IsAny()), Times.Once); + It.IsAny()), + Times.Once); - _js.Verify(x => x.InvokeAsync( - It.IsAny(), - It.IsAny(), - It.IsAny()), Times.Never); + VerifyRequests(Times.Never()); + + task.IsCompleted.Should().BeFalse(); bootstrapCompleted.SetResult(); await task; - _js.Verify(x => x.InvokeAsync( - "uauth.resourceRequest", - It.IsAny(), - It.IsAny()), Times.Once); + VerifyRequests(Times.Once()); } [Fact] @@ -92,17 +177,15 @@ public async Task Send_Should_Pass_Correct_Arguments_To_JS() { object? capturedOptions = null; + _tokenStore.Replace(Token("access-token")); + _js.Setup(x => x.InvokeAsync( - "uauth.resourceRequest", + ResourceRequest, It.IsAny(), It.IsAny())) .Callback( (_, _, args) => capturedOptions = args[0]) - .ReturnsAsync(new UAuthResourceTransportResult - { - Ok = true, - Status = 201 - }); + .ReturnsAsync(Success(201)); var payload = new { Name = "Product" }; @@ -112,37 +195,35 @@ public async Task Send_Should_Pass_Correct_Arguments_To_JS() await client.SendAsync( "POST", - "/api/products", - payload, ct: TestContext.Current.CancellationToken); + ResourceEndpoint, + payload, + ct: TestContext.Current.CancellationToken); capturedOptions.Should().NotBeNull(); - var type = capturedOptions!.GetType(); - - type.GetProperty("url")! - .GetValue(capturedOptions) - .Should().Be("/api/products"); + ReadArgument(capturedOptions!, "url") + .Should().Be(ResourceEndpoint); - type.GetProperty("method")! - .GetValue(capturedOptions) + ReadArgument(capturedOptions!, "method") .Should().Be("POST"); - type.GetProperty("baseAddress")! - .GetValue(capturedOptions) + ReadArgument(capturedOptions!, "baseAddress") .Should().Be("https://localhost:6120"); - type.GetProperty("credentials")! - .GetValue(capturedOptions) + ReadArgument(capturedOptions!, "credentials") .Should().Be("Include"); - type.GetProperty("payload")! - .GetValue(capturedOptions) + ReadArgument(capturedOptions!, "payload") .Should().BeSameAs(payload); - var requestId = type.GetProperty("requestId")! - .GetValue(capturedOptions) as string; + ReadArgument(capturedOptions!, "accessToken") + .Should().Be("access-token"); + + var requestId = ReadArgument( + capturedOptions!, "requestId"); requestId.Should().NotBeNullOrWhiteSpace(); + Guid.TryParseExact(requestId, "N", out _) .Should().BeTrue(); } @@ -160,30 +241,47 @@ public async Task Send_Should_Return_Success_Response() SetupResponse(response); - var result = await CreateClient() - .SendAsync("GET", "/api/products/1", ct: TestContext.Current.CancellationToken); + var result = await CreateClient().SendAsync( + "GET", + "/api/products/1", + ct: TestContext.Current.CancellationToken); result.Should().BeSameAs(response); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); } - [Fact] - public async Task Send_Should_Return_Http_Error_Response() + [Theory] + [InlineData(400)] + [InlineData(401)] + [InlineData(403)] + [InlineData(404)] + [InlineData(409)] + [InlineData(429)] + [InlineData(500)] + public async Task Send_Should_Return_Http_Error_Without_Recovery( + int status) { var response = new UAuthResourceTransportResult { Ok = false, - Status = 403, - Body = """{"title":"Forbidden"}""" + Status = status }; SetupResponse(response); - var result = await CreateClient() - .SendAsync("GET", "/api/products", ct: TestContext.Current.CancellationToken); + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); result.Should().BeSameAs(response); - result.Status.Should().Be(403); + result.Status.Should().Be(status); result.Ok.Should().BeFalse(); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); } [Fact] @@ -193,11 +291,15 @@ public async Task Send_Should_Throw_When_JS_Returns_Null() var client = CreateClient(); - Func act = () => - client.SendAsync("GET", "/api/products"); + Func act = () => client.SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); await act.Should() .ThrowAsync(); + + VerifyRecovery(Times.Never()); } [Fact] @@ -211,13 +313,53 @@ public async Task Send_Should_Throw_On_Network_Error() var client = CreateClient(); - Func act = () => - client.SendAsync("GET", "/api/products"); + Func act = () => client.SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); await act.Should() .ThrowAsync(); + + VerifyRecovery(Times.Never()); } + [Fact] + public async Task Send_Should_Generate_Unique_RequestIds() + { + var requestIds = new List(); + + _js.Setup(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny())) + .Callback( + (_, _, args) => + { + requestIds.Add( + ReadArgument( + args[0]!, "requestId")!); + }) + .ReturnsAsync(Success()); + + var client = CreateClient(); + var ct = TestContext.Current.CancellationToken; + + await client.SendAsync( + "GET", "/api/products/1", ct: ct); + + await client.SendAsync( + "GET", "/api/products/2", ct: ct); + + requestIds.Should().HaveCount(2); + requestIds.Distinct().Should().HaveCount(2); + requestIds.All(id => Guid.TryParseExact(id, "N", out _)).Should().BeTrue(); + } + + // ------------------------------------------------------------ + // Cancellation + // ------------------------------------------------------------ + [Fact] public async Task Send_Should_Not_Bootstrap_When_Already_Cancelled() { @@ -226,29 +368,30 @@ public async Task Send_Should_Not_Bootstrap_When_Already_Cancelled() var client = CreateClient(); - Func act = () => - client.SendAsync( - "GET", - "/api/products", - ct: cts.Token); + Func act = () => client.SendAsync( + "GET", + ResourceEndpoint, + ct: cts.Token); await act.Should() .ThrowAsync(); + _requestRecovery.Verify(x => x.PrepareAsync( + It.IsAny()), + Times.Never); + _bootstrapper.Verify(x => x.EnsureStartedAsync( - It.IsAny()), Times.Never); + It.IsAny()), + Times.Never); - _js.Verify(x => x.InvokeAsync( - It.IsAny(), - It.IsAny(), - It.IsAny()), Times.Never); + VerifyRequests(Times.Never()); } [Fact] public async Task Send_Should_Not_Invoke_JS_When_Cancelled_During_Bootstrap() { - var bootstrapCompleted = - new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var bootstrapCompleted = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); _bootstrapper .Setup(x => x.EnsureStartedAsync( @@ -261,9 +404,13 @@ public async Task Send_Should_Not_Invoke_JS_When_Cancelled_During_Bootstrap() var task = client.SendAsync( "GET", - "/api/products", + ResourceEndpoint, ct: cts.Token); + _bootstrapper.Verify(x => x.EnsureStartedAsync( + It.IsAny()), + Times.Once); + cts.Cancel(); bootstrapCompleted.SetResult(); @@ -273,10 +420,7 @@ public async Task Send_Should_Not_Invoke_JS_When_Cancelled_During_Bootstrap() await act.Should() .ThrowAsync(); - _js.Verify(x => x.InvokeAsync( - It.IsAny(), - It.IsAny(), - It.IsAny()), Times.Never); + VerifyRequests(Times.Never()); } [Fact] @@ -285,59 +429,622 @@ public async Task Send_Should_Propagate_JS_Cancellation() using var cts = new CancellationTokenSource(); _js.Setup(x => x.InvokeAsync( - "uauth.resourceRequest", + ResourceRequest, cts.Token, It.IsAny())) .Returns( - (_, ct, _) => new ValueTask( - Task.FromCanceled(ct))); + (_, ct, _) => + { + cts.Cancel(); - var client = CreateClient(); + return new ValueTask( + Task.FromCanceled( + ct)); + }); - cts.Cancel(); + var client = CreateClient(); - // The pre-cancelled token is rejected before JS invocation. - Func act = () => - client.SendAsync( - "GET", - "/api/products", - ct: cts.Token); + Func act = () => client.SendAsync( + "GET", + ResourceEndpoint, + ct: cts.Token); await act.Should() .ThrowAsync(); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); } + // ------------------------------------------------------------ + // Request preparation / proactive refresh + // ------------------------------------------------------------ + [Fact] - public async Task Send_Should_Generate_Unique_RequestIds() + public async Task Send_Should_Wait_For_Preparation_Before_Bootstrap() { - var requestIds = new List(); + var preparationCompleted = + new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _requestRecovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .Returns(preparationCompleted.Task); + + SetupResponse(Success()); + + var client = CreateClient(); + + var task = client.SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + task.IsCompleted.Should().BeFalse(); + + _bootstrapper.Verify(x => x.EnsureStartedAsync( + It.IsAny()), + Times.Never); + + VerifyRequests(Times.Never()); + + preparationCompleted.SetResult( + new UAuthRequestPreparationResult( + _tokenStore.Capture())); + + await task; + + _bootstrapper.Verify(x => x.EnsureStartedAsync( + It.IsAny()), + Times.Once); + + VerifyRequests(Times.Once()); + } + + [Fact] + public async Task Send_Should_Use_Token_Rotated_During_Preparation() + { + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + + _requestRecovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.TryRotate( + expected, + Token("proactive-token")) + .Should().BeTrue(); + + return new UAuthRequestPreparationResult( + _tokenStore.Capture()); + }); + + object? capturedOptions = null; _js.Setup(x => x.InvokeAsync( - "uauth.resourceRequest", + ResourceRequest, It.IsAny(), It.IsAny())) .Callback( + (_, _, args) => capturedOptions = args[0]) + .ReturnsAsync(Success()); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Ok.Should().BeTrue(); + + capturedOptions.Should().NotBeNull(); + + ReadArgument(capturedOptions!, "accessToken") + .Should().Be("proactive-token"); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); + } + + [Theory] + [InlineData(401, 401)] + [InlineData(429, 429)] + [InlineData(503, 503)] + [InlineData(0, 401)] + public async Task Send_Should_Return_Preparation_Failure_Without_JS( + int refreshStatus, + int expectedStatus) + { + _requestRecovery + .Setup(x => x.PrepareAsync( + It.IsAny())) + .ReturnsAsync(() => + new UAuthRequestPreparationResult( + _tokenStore.Capture(), + new RefreshResult + { + IsSuccess = false, + Status = refreshStatus, + RetryAfter = refreshStatus == 429 + ? TimeSpan.FromSeconds(30) + : null + })); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Ok.Should().BeFalse(); + result.Status.Should().Be(expectedStatus); + + if (refreshStatus == 429) + { + result.RetryAfter.Should().Be("30"); + } + + _bootstrapper.Verify(x => x.EnsureStartedAsync( + It.IsAny()), + Times.Never); + + VerifyRequests(Times.Never()); + VerifyRecovery(Times.Never()); + } + + // ------------------------------------------------------------ + // Reactive refresh and replay + // ------------------------------------------------------------ + + [Theory] + [InlineData("GET")] + [InlineData("POST")] + [InlineData("PUT")] + [InlineData("PATCH")] + [InlineData("DELETE")] + public async Task Send_Should_Replay_Once_After_Successful_Recovery( + string method) + { + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + + object? payload = method == "GET" + ? null + : new { Name = "Product" }; + + var requests = new List(); + + var challenge = Challenge(); + var success = Success(); + + _js.Setup(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny())) + .Returns( (_, _, args) => { - var options = args[0]!; - var requestId = options.GetType() - .GetProperty("requestId")! - .GetValue(options) as string; + requests.Add(args[0]!); - requestIds.Add(requestId!); - }) - .ReturnsAsync(new UAuthResourceTransportResult + return new ValueTask( + requests.Count == 1 + ? challenge + : success); + }); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => { - Ok = true, - Status = 200 + _tokenStore.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + return _tokenStore.Capture(); + }); + + var result = await CreateClient().SendAsync( + method, + ResourceEndpoint, + payload, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(success); + + requests.Should().HaveCount(2); + + ReadArgument(requests[0], "accessToken") + .Should().Be("old-token"); + + ReadArgument(requests[1], "accessToken") + .Should().Be("new-token"); + + foreach (var request in requests) + { + ReadArgument(request, "method") + .Should().Be(method); + + ReadArgument(request, "url") + .Should().Be(ResourceEndpoint); + + if (payload is null) + { + ReadArgument(request, "payload") + .Should().BeNull(); + } + else + { + ReadArgument(request, "payload") + .Should().BeSameAs(payload); + } + } + + ReadArgument(requests[0], "requestId") + .Should().NotBe( + ReadArgument(requests[1], "requestId")); + + VerifyRequests(Times.Exactly(2)); + + _requestRecovery.Verify(x => x.RecoverAsync( + expected, + It.IsAny()), + Times.Once); + + _requestRecovery.Verify(x => x.PrepareAsync( + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Send_Should_Not_Recover_When_Reactive_Is_Disabled() + { + _tokenStore.Replace(Token("old-token")); + + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateClient(reactive: false) + .SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); + } + + [Fact] + public async Task Send_Should_Return_Original_401_When_Recovery_Fails() + { + _tokenStore.Replace(Token("old-token")); + + var challenge = Challenge(); + + SetupResponse(challenge); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Once()); + } + + [Fact] + public async Task Send_Should_Not_Retry_Again_When_Replay_Returns_401() + { + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + + var firstChallenge = Challenge(); + var secondChallenge = Challenge(); + + _js.SetupSequence(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny())) + .ReturnsAsync(firstChallenge) + .ReturnsAsync(secondChallenge); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + return _tokenStore.Capture(); + }); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(secondChallenge); + + VerifyRequests(Times.Exactly(2)); + VerifyRecovery(Times.Once()); + } + + // ------------------------------------------------------------ + // Authentication lifecycle safety + // ------------------------------------------------------------ + + [Fact] + public async Task Send_Should_Not_Recover_When_Epoch_Changes_During_Request() + { + _tokenStore.Replace(Token("old-token")); + + var challenge = Challenge(); + + _js.Setup(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny())) + .Returns(() => + { + _tokenStore.Replace(Token("another-user-token")); + + return new ValueTask( + challenge); + }); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Never()); + + _tokenStore.Read()!.Token + .Should().Be("another-user-token"); + } + + [Fact] + public async Task Send_Should_Not_Replay_When_Epoch_Changes_During_Recovery() + { + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + var challenge = Challenge(); + + SetupResponse(challenge); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.Replace(Token("another-user-token")); + + return _tokenStore.Capture(); + }); + + var result = await CreateClient().SendAsync( + "POST", + ResourceEndpoint, + new { Name = "Product" }, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Once()); + + _tokenStore.Read()!.Token + .Should().Be("another-user-token"); + } + + [Fact] + public async Task Send_Should_Not_Replay_When_Recovered_Token_Is_Expired() + { + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + var challenge = Challenge(); + + SetupResponse(challenge); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.TryRotate( + expected, + new AccessToken + { + Token = "expired-token", + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-1) + }) + .Should().BeTrue(); + + return _tokenStore.Capture(); + }); + + var result = await CreateClient().SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Once()); + } + + [Fact] + public async Task Send_Should_Not_Replay_When_Cancelled_During_Recovery() + { + using var cts = new CancellationTokenSource(); + + _tokenStore.Replace(Token("old-token")); + + var expected = _tokenStore.Capture(); + + SetupResponse(Challenge()); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.TryRotate( + expected, + Token("new-token")) + .Should().BeTrue(); + + cts.Cancel(); + + return _tokenStore.Capture(); }); var client = CreateClient(); - await client.SendAsync("GET", "/api/products/1", ct: TestContext.Current.CancellationToken); - await client.SendAsync("GET", "/api/products/2", ct: TestContext.Current.CancellationToken); + Func act = () => client.SendAsync( + "GET", + ResourceEndpoint, + ct: cts.Token); - requestIds.Should().HaveCount(2); - requestIds.Distinct().Should().HaveCount(2); + await act.Should() + .ThrowAsync(); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Once()); + } + + [Fact] + public async Task Send_Should_Recover_Actual_Sent_Token_When_Rotated_During_Bootstrap() + { + _tokenStore.Replace(Token("old-token")); + + var original = _tokenStore.Capture(); + + var bootstrapCompletion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + + _bootstrapper + .Setup(x => x.EnsureStartedAsync( + It.IsAny())) + .Returns(bootstrapCompletion.Task); + + var sentTokens = new List(); + + _js.Setup(x => x.InvokeAsync( + ResourceRequest, + It.IsAny(), + It.IsAny())) + .Returns( + (_, _, args) => + { + sentTokens.Add( + ReadArgument( + args[0]!, "accessToken")); + + return new ValueTask( + Challenge()); + }); + + var client = CreateClient(); + + var operation = client.SendAsync( + "GET", + ResourceEndpoint, + ct: TestContext.Current.CancellationToken); + + _tokenStore.TryRotate( + original, + Token("new-token")).Should().BeTrue(); + + var actualSentSnapshot = _tokenStore.Capture(); + + // Simulate recovery of the older token. This must not + // accidentally authorize replaying the already rejected token. + _requestRecovery + .Setup(x => x.RecoverAsync( + original, + It.IsAny())) + .ReturnsAsync(actualSentSnapshot); + + bootstrapCompletion.SetResult(); + + var result = await operation; + + result.Status.Should().Be(401); + + // The server rejected new-token. Returning the same token + // from recovery must not cause an identical second request. + sentTokens.Should().ContainSingle(); + sentTokens[0].Should().Be("new-token"); + + _requestRecovery.Verify(x => x.RecoverAsync( + actualSentSnapshot, + It.IsAny()), + Times.Once); + } + + [Fact] + public async Task Send_Should_Not_Replay_When_Recovery_Returns_Same_Token() + { + _tokenStore.Replace(Token("original-token")); + + var expected = _tokenStore.Capture(); + + var challenge = Challenge(); + + SetupResponse(challenge); + + _requestRecovery + .Setup(x => x.RecoverAsync( + expected, + It.IsAny())) + .ReturnsAsync(() => + { + _tokenStore.TryRotate( + expected, + Token("original-token")) + .Should().BeTrue(); + + return _tokenStore.Capture(); + }); + + var result = await CreateClient().SendAsync( + "POST", + ResourceEndpoint, + new { Name = "Product" }, + ct: TestContext.Current.CancellationToken); + + result.Should().BeSameAs(challenge); + + VerifyRequests(Times.Once()); + VerifyRecovery(Times.Once()); + + _tokenStore.Capture().Generation + .Should().Be(expected.Generation + 1); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResultMapperTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResultMapperTests.cs index 3fa289ae..b476fc69 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResultMapperTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthResultMapperTests.cs @@ -1,8 +1,8 @@ -using CodeBeam.UltimateAuth.Client.Contracts; -using CodeBeam.UltimateAuth.Client.Errors; +using CodeBeam.UltimateAuth.Client.Errors; using CodeBeam.UltimateAuth.Client.Infrastructure; using AwesomeAssertions; using System.Text.Json; +using CodeBeam.UltimateAuth.Client; namespace CodeBeam.UltimateAuth.Tests.Unit; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthStateManagerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthStateManagerTests.cs index ec0f508c..3207b73a 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthStateManagerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthStateManagerTests.cs @@ -2,7 +2,6 @@ using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Abstractions; using CodeBeam.UltimateAuth.Client.Authentication; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; @@ -63,6 +62,8 @@ public async Task EnsureAsync_Should_Deduplicate_InFlight_Calls_But_Allow_Later_ using (manager) { + var ct = TestContext.Current.CancellationToken; + var pendingValidation = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously); @@ -75,14 +76,13 @@ public async Task EnsureAsync_Should_Deduplicate_InFlight_Calls_But_Allow_Later_ Snapshot = CreateSnapshot() }); - var first = manager.EnsureAsync(force: true, ct: TestContext.Current.CancellationToken); - var second = manager.EnsureAsync(force: true, ct: TestContext.Current.CancellationToken); - var third = manager.EnsureAsync(force: true, ct: TestContext.Current.CancellationToken); + var first = manager.EnsureAsync(force: true, ct: ct); + var second = manager.EnsureAsync(force: true, ct: ct); + var third = manager.EnsureAsync(force: true, ct: ct); first.IsCompleted.Should().BeFalse(); - - second.Should().BeSameAs(first); - third.Should().BeSameAs(first); + second.IsCompleted.Should().BeFalse(); + third.IsCompleted.Should().BeFalse(); flows.Verify( x => x.ValidateAsync(), @@ -98,7 +98,11 @@ public async Task EnsureAsync_Should_Deduplicate_InFlight_Calls_But_Allow_Later_ manager.State.IsAuthenticated.Should().BeTrue(); - await manager.EnsureAsync(force: true, ct: TestContext.Current.CancellationToken); + flows.Verify( + x => x.ValidateAsync(), + Times.Once); + + await manager.EnsureAsync(force: true, ct: ct); flows.Verify( x => x.ValidateAsync(), @@ -577,36 +581,60 @@ public async Task InitialValidation_NotFound_RecoversToken_AndRevalidates() }); var store = new InMemoryUAuthTokenStore(); + var expected = store.Capture(); - flows.Setup(x => x.RecoverAsync()) - .Callback(() => store.Replace(new AccessToken - { - Token = "recovered-jwt", - Format = TokenFormat.Jwt, - ExpiresAt = DateTimeOffset.UtcNow.AddHours(1) - })) - .ReturnsAsync(new RefreshResult + var now = DateTimeOffset.UtcNow; + + var clock = new Mock(); + clock.SetupGet(x => x.UtcNow).Returns(now); + + var refresh = new Mock(); + + refresh.Setup(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Recovery, + expected, + It.IsAny())) + .ReturnsAsync(() => { - IsSuccess = true, - Status = 200, - Outcome = RefreshOutcome.Success + var rotated = store.TryRotate( + expected, + new AccessToken + { + Token = "recovered-jwt", + Format = TokenFormat.Jwt, + ExpiresAt = now.AddHours(1) + }); + + rotated.Should().BeTrue(); + + return new RefreshResult + { + IsSuccess = true, + Status = 204, + Outcome = RefreshOutcome.Success + }; }); var client = new Mock(); client.SetupGet(x => x.Flows).Returns(flows.Object); var transport = new Mock(); + transport.Setup(x => x.GetLoginTransportAsync( - It.IsAny(), It.IsAny())) + It.IsAny(), + It.IsAny())) .ReturnsAsync(new UAuthLoginTransportInfo { Supported = true, AccessTokenInHeader = true }); - var clock = new Mock(); - clock.SetupGet(x => x.UtcNow) - .Returns(DateTimeOffset.UtcNow); + var options = Options.Create(new UAuthClientOptions()); + + var schedule = new UAuthRefreshSchedule( + store, + options, + clock.Object); using var manager = new UAuthStateManager( client.Object, @@ -614,16 +642,32 @@ public async Task InitialValidation_NotFound_RecoversToken_AndRevalidates() clock.Object, store, transport.Object, - Options.Create(new UAuthClientOptions())); + schedule, + refresh.Object, + options); await manager.EnsureAsync( ct: TestContext.Current.CancellationToken); manager.State.IsAuthenticated.Should().BeTrue(); - store.Read()!.Token.Should().Be("recovered-jwt"); - flows.Verify(x => x.RecoverAsync(), Times.Once); - flows.Verify(x => x.ValidateAsync(), Times.Exactly(2)); + var current = store.Capture(); + + current.Token!.Token.Should().Be("recovered-jwt"); + current.Epoch.Should().Be(expected.Epoch); + current.Generation.Should().Be(expected.Generation + 1); + + schedule.IsAuthenticated(current).Should().BeTrue(); + + refresh.Verify(x => x.RefreshIfCurrentAsync( + UAuthRefreshTrigger.Recovery, + expected, + It.IsAny()), + Times.Once); + + flows.Verify( + x => x.ValidateAsync(), + Times.Exactly(2)); } [Fact] @@ -640,18 +684,24 @@ public async Task InitialValidation_WithExistingToken_DoesNotRecover() var client = new Mock(); client.SetupGet(x => x.Flows).Returns(flows.Object); + var now = DateTimeOffset.UtcNow; + var store = new InMemoryUAuthTokenStore(); store.Replace(new AccessToken { Token = "existing-jwt", Format = TokenFormat.Jwt, - ExpiresAt = DateTimeOffset.UtcNow.AddHours(1) + ExpiresAt = now.AddHours(1) }); + var expected = store.Capture(); + var transport = new Mock(); + transport.Setup(x => x.GetLoginTransportAsync( - It.IsAny(), It.IsAny())) + It.IsAny(), + It.IsAny())) .ReturnsAsync(new UAuthLoginTransportInfo { Supported = true, @@ -659,8 +709,16 @@ public async Task InitialValidation_WithExistingToken_DoesNotRecover() }); var clock = new Mock(); - clock.SetupGet(x => x.UtcNow) - .Returns(DateTimeOffset.UtcNow); + clock.SetupGet(x => x.UtcNow).Returns(now); + + var refresh = new Mock(); + + var options = Options.Create(new UAuthClientOptions()); + + var schedule = new UAuthRefreshSchedule( + store, + options, + clock.Object); using var manager = new UAuthStateManager( client.Object, @@ -668,14 +726,37 @@ public async Task InitialValidation_WithExistingToken_DoesNotRecover() clock.Object, store, transport.Object, - Options.Create(new UAuthClientOptions())); + schedule, + refresh.Object, + options); await manager.EnsureAsync( ct: TestContext.Current.CancellationToken); - flows.Verify(x => x.RecoverAsync(), Times.Never); + refresh.Verify(x => x.RefreshIfCurrentAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + + transport.Verify(x => x.GetLoginTransportAsync( + It.IsAny(), + It.IsAny()), + Times.Never); + + flows.Verify( + x => x.ValidateAsync(), + Times.Once); manager.State.IsAuthenticated.Should().BeFalse(); + + var current = store.Capture(); + + current.Token.Should().BeNull(); + current.Epoch.Should().Be(expected.Epoch + 1); + current.Generation.Should().Be(expected.Generation + 1); + + schedule.IsAuthenticated(current).Should().BeFalse(); } @@ -724,13 +805,22 @@ private static UAuthStateManager NewManager(IUAuthClient client, IUAuthClientEve AccessTokenInHeader = false }); + var store = new InMemoryUAuthTokenStore(); + + var options = Options.Create(new UAuthClientOptions()); + var schedule = new UAuthRefreshSchedule(store, options, clock); + + var refresh = new Mock(); + return new UAuthStateManager( client, events, clock, - new InMemoryUAuthTokenStore(), + store, requestClient.Object, - Options.Create(new UAuthClientOptions())); + schedule, + refresh.Object, + options); } private static void SetupValidSnapshot(Mock flows, AuthStateSnapshot? snapshot = null) diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs index 6725b8ed..5bb853b4 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthTokenStoreTests.cs @@ -1,5 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Infrastructure; +using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Core.Contracts; namespace CodeBeam.UltimateAuth.Tests.Unit; @@ -71,6 +70,84 @@ public void Expiration_uses_issuer_metadata() Assert.True(token.IsExpired(now.AddSeconds(601))); } + [Fact] + public void Rotation_changes_generation_but_not_epoch() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(Token("old")); + + var before = store.Capture(); + + Assert.True(store.TryRotate(before, Token("new"))); + + var after = store.Capture(); + + Assert.Equal(before.Epoch, after.Epoch); + Assert.Equal(before.Generation + 1, after.Generation); + Assert.Equal("new", after.Token!.Token); + } + + [Fact] + public void Logout_prevents_stale_refresh_from_restoring_token() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(Token("old")); + + var before = store.Capture(); + + store.Clear(); + + Assert.False(store.TryRotate(before, Token("rotated"))); + Assert.Null(store.Read()); + } + + [Fact] + public void New_login_prevents_previous_refresh_from_replacing_token() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(Token("user-a")); + + var before = store.Capture(); + + store.Replace(Token("user-b")); + + Assert.False(store.TryRotate(before, Token("user-a-rotated"))); + Assert.Equal("user-b", store.Read()!.Token); + } + + [Fact] + public void Stale_failure_cannot_clear_new_login() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(Token("user-a")); + + var before = store.Capture(); + + store.Replace(Token("user-b")); + + Assert.False(store.TryClear(before)); + Assert.Equal("user-b", store.Read()!.Token); + } + + [Fact] + public void Same_snapshot_cannot_be_rotated_twice() + { + var store = new InMemoryUAuthTokenStore(); + + store.Replace(Token("old")); + + var before = store.Capture(); + + Assert.True(store.TryRotate(before, Token("first"))); + Assert.False(store.TryRotate(before, Token("second"))); + + Assert.Equal("first", store.Read()!.Token); + } + private static AccessToken CreateToken(string value) => new() { @@ -78,4 +155,12 @@ private static AccessToken CreateToken(string value) Format = TokenFormat.Jwt, ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5) }; + + private static AccessToken Token(string value) + => new() + { + Token = value, + Format = TokenFormat.Jwt, + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(10) + }; } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthUrlBuilderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthUrlBuilderTests.cs index 0a7a7054..cdf05a31 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthUrlBuilderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Client/UAuthUrlBuilderTests.cs @@ -1,4 +1,4 @@ -using CodeBeam.UltimateAuth.Client.Contracts; +using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Infrastructure; using CodeBeam.UltimateAuth.Client.Options; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Fake/FakeFlowClient.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Fake/FakeFlowClient.cs index 92fb69cd..92813f3e 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Fake/FakeFlowClient.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Fake/FakeFlowClient.cs @@ -1,5 +1,4 @@ using CodeBeam.UltimateAuth.Client; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Services; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/UAuthClientTestBase.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/UAuthClientTestBase.cs index e92ef6b8..4ea4618b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/UAuthClientTestBase.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/UAuthClientTestBase.cs @@ -1,6 +1,5 @@ using CodeBeam.UltimateAuth.Client; using CodeBeam.UltimateAuth.Client.Abstractions; -using CodeBeam.UltimateAuth.Client.Contracts; using CodeBeam.UltimateAuth.Client.Diagnostics; using CodeBeam.UltimateAuth.Client.Events; using CodeBeam.UltimateAuth.Client.Infrastructure; @@ -47,7 +46,10 @@ protected IUAuthClient CreateClient( ); } - protected IFlowClient CreateFlowClient(Mock? requestMock = null, Mock? eventsMock = null) + protected IFlowClient CreateFlowClient( + Mock? requestMock = null, + Mock? eventsMock = null, + bool backgroundRefreshDue = false) { var request = requestMock ?? Request; var events = eventsMock ?? Events; @@ -93,14 +95,24 @@ protected IFlowClient CreateFlowClient(Mock? requestMock = var diagnostics = new UAuthClientDiagnostics(); + var tokenStore = new InMemoryUAuthTokenStore(); + + var refreshCoordinator = CreateRefreshCoordinator( + request.Object, + events.Object, + tokenStore, + diagnostics, + "/auth/refresh", + backgroundRefreshDue); + return new UAuthFlowClient( request.Object, events.Object, deviceProvider.Object, returnUrlProvider.Object, options, - diagnostics, - new InMemoryUAuthTokenStore()); + tokenStore, + refreshCoordinator); } protected IUAuthClient CreateCredentialClient() @@ -176,4 +188,54 @@ protected static UAuthTransportResult SuccessJson(T body) Status = 200, Body = JsonSerializer.SerializeToElement(body) }; + + protected static IUAuthRefreshCoordinator CreateRefreshCoordinator( + IUAuthRequestClient request, + IUAuthClientEvents events, + IUAuthTokenStore tokenStore, + UAuthClientDiagnostics diagnostics, + string refreshEndpoint, + bool backgroundRefreshDue = false) + { + var transport = new Mock(); + + transport + .Setup(x => x.SendAsync(It.IsAny())) + .Returns((CancellationToken ct) => + request.SendFormAsync( + refreshEndpoint, + form: null, + ct: ct)); + + var interval = TimeSpan.FromMinutes(5); + + var options = Options.Create(new UAuthClientOptions + { + AutoRefresh = new UAuthClientAutoRefreshOptions + { + Background = true, + Interval = interval + } + }); + + var clock = new TestClock(); + + var schedule = new UAuthRefreshSchedule(tokenStore, options, clock); + + if (backgroundRefreshDue) + { + schedule.MarkAuthenticated(); + clock.Advance(interval); + } + + var executor = new UAuthRefreshExecutor( + transport.Object, + events, + tokenStore, + schedule, + diagnostics, + clock); + + return new UAuthRefreshCoordinator(executor, tokenStore, schedule); + } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs index a6942115..2efe24a4 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs @@ -90,8 +90,7 @@ public void Each_Call_Returns_New_EffectiveOptions_Instance() [InlineData(UAuthMode.Hybrid)] [InlineData(UAuthMode.SemiHybrid)] [InlineData(UAuthMode.PureJwt)] - public void Effective_options_should_apply_defaults_for_each_auth_mode( - UAuthMode mode) + public void Effective_options_should_apply_defaults_for_each_auth_mode(UAuthMode mode) { var original = new UAuthServerOptions(); var provider = CreateProviderForMode(original, mode); @@ -152,8 +151,8 @@ public void SemiHybrid_should_apply_expected_token_defaults() token.IssueJwt.Should().BeTrue(); token.IssueOpaque.Should().BeTrue(); token.AddJwtIdClaim.Should().BeTrue(); - token.AccessTokenLifetime.Should().Be(TimeSpan.FromMinutes(10)); - token.RefreshTokenLifetime.Should().Be(TimeSpan.FromDays(7)); + token.AccessTokenLifetime.Should().Be(TimeSpan.FromHours(1)); + token.RefreshTokenLifetime.Should().Be(TimeSpan.FromHours(2)); } [Fact] @@ -467,6 +466,37 @@ public void Clone_should_not_share_profile_mode_mappings() .Should().Be(UAuthMode.PureJwt); } + [Theory] + [InlineData(UAuthMode.Hybrid)] + [InlineData(UAuthMode.SemiHybrid)] + [InlineData(UAuthMode.PureJwt)] + public void Effective_options_should_preserve_explicit_token_lifetimes(UAuthMode mode) + { + var original = new UAuthServerOptions + { + AuthMode = mode, + Token = + { + AccessTokenLifetime = TimeSpan.FromSeconds(30), + RefreshTokenLifetime = TimeSpan.FromHours(2) + } + }; + + var provider = CreateProviderForMode(original, mode); + + var effective = provider.GetEffective( + TenantKey.Single, + UAuthApplicationProfile.BlazorServer); + + effective.Mode.Should().Be(mode); + + effective.Options.Token.AccessTokenLifetime + .Should().Be(TimeSpan.FromSeconds(30)); + + effective.Options.Token.RefreshTokenLifetime + .Should().Be(TimeSpan.FromHours(2)); + } + private static EffectiveServerOptionsProvider CreateProviderForMode( UAuthServerOptions options, UAuthMode mode) diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/BearerSessionIdResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/BearerSessionIdResolverTests.cs index 65485d9e..5d18fe14 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/BearerSessionIdResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/BearerSessionIdResolverTests.cs @@ -114,4 +114,20 @@ public void Resolve_WhenBearerValueContainsOuterWhitespace_ShouldTrimAndResolve( result.Should().NotBeNull(); result!.Value.ToString().Should().Be(ValidSessionId); } + + [Fact] + public void Resolve_WhenBearerContainsJwt_ShouldReturnNull() + { + var sut = new BearerSessionIdResolver(); + var context = new DefaultHttpContext(); + + context.Request.Headers.Authorization = + "Bearer eyJhbGciOiJIUzI1NiJ9." + + "eyJzdWIiOiIxMjMifQ." + + "abcdefghijklmnopqrstuv"; + + var result = sut.Resolve(context); + + result.Should().BeNull(); + } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/CompositeSessionIdResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/CompositeSessionIdResolverTests.cs index 35cf2be7..4a7a3798 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/CompositeSessionIdResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/CompositeSessionIdResolverTests.cs @@ -191,7 +191,8 @@ public async Task ResolveAsync_ShouldRespectEffectiveCookieSetting( [Fact] public async Task ResolveAsync_ShouldReadApplicationProfileAndUseItsEffectiveOptions() { - var expected = CreateSessionId("cookie-session-000000000000000000000002"); + var expected = CreateSessionId( + "cookie-session-000000000000000000000002"); var cookie = CreateResolver("Cookie", expected); @@ -217,9 +218,13 @@ public async Task ResolveAsync_ShouldReadApplicationProfileAndUseItsEffectiveOpt var sut = new CompositeSessionIdResolver( new[] { cookie.Object }, profileReader.Object, - effectiveProvider.Object); + effectiveProvider.Object, + Mock.Of(), + Mock.Of()); - var result = await sut.ResolveAsync(context, ct: TestContext.Current.CancellationToken); + var result = await sut.ResolveAsync( + context, + ct: TestContext.Current.CancellationToken); result.Should().Be(expected); @@ -249,19 +254,15 @@ private static UAuthServerOptions CreateOptions(params string[] order) return options; } - private static (CompositeSessionIdResolver Sut, DefaultHttpContext Context) - CreateSut( - UAuthServerOptions effectiveOptions, - params IInnerSessionIdResolver[] resolvers) + private static (CompositeSessionIdResolver Sut, DefaultHttpContext Context) CreateSut(UAuthServerOptions effectiveOptions, params IInnerSessionIdResolver[] resolvers) { var context = new DefaultHttpContext(); var profileReader = new Mock(); - profileReader - .Setup(x => x.ReadAsync(context)) - .ReturnsAsync(Profile); + profileReader.Setup(x => x.ReadAsync(context)).ReturnsAsync(Profile); var effectiveProvider = new Mock(); + effectiveProvider .Setup(x => x.GetEffective(context, Profile)) .Returns(new EffectiveUAuthServerOptions @@ -273,7 +274,9 @@ private static (CompositeSessionIdResolver Sut, DefaultHttpContext Context) var sut = new CompositeSessionIdResolver( resolvers, profileReader.Object, - effectiveProvider.Object); + effectiveProvider.Object, + Mock.Of(), + Mock.Of()); return (sut, context); } @@ -281,11 +284,8 @@ private static (CompositeSessionIdResolver Sut, DefaultHttpContext Context) private static Mock CreateResolver(string name, AuthSessionId? result) { var resolver = new Mock(); - resolver.SetupGet(x => x.Name).Returns(name); - resolver.Setup(x => x.Resolve(It.IsAny())).Returns(result); - return resolver; }