Skip to content
Merged

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
});
}

Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using CodeBeam.UltimateAuth.Client.Infrastructure;
using CodeBeam.UltimateAuth.Client.Abstractions;
using System.Text.Json;

namespace CodeBeam.UltimateAuth.IdentityLab.Services;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, int> DeviceTypeLimits,
DeviceLimitBehavior DeviceLimitBehavior);
Expand All @@ -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<string, int>(serverOptions.Value.DeviceLimits.TypeLimits, StringComparer.OrdinalIgnoreCase),
new Dictionary<string, int>(
serverOptions.Value.DeviceLimits.TypeLimits,
StringComparer.OrdinalIgnoreCase),
serverOptions.Value.DeviceLimits.Behavior);
}
}
15 changes: 12 additions & 3 deletions docs/content/auth-flows/refresh-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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.

Expand Down
Loading
Loading