Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions docs/content/client-sdk/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,113 @@ For application-specific workflows that cannot be expressed through the componen

**Solution:** Use the appropriate authentication state integration for UI rendering, and reserve explicit validation for operations that require it.

## Blazor WebAssembly with a PureJwt Hub

Enable the opt-in browser token flow in the WebAssembly app.

```csharp
builder.Services.AddUltimateAuthClientBlazor(options =>
{
options.UsePureJwtBrowserTokens = true;
options.Pkce.Enabled = true;
options.Endpoints.BasePath = "https://auth.example.com/auth";
options.Resource.BaseAddress = "https://api.example.com";
});
```

Keep `UAuthApp` around the router and protected content. Start interactive login with
`await UAuthClient.Flows.BeginPkceAsync()`. The Hub completes the existing PKCE
flow, sets the HttpOnly refresh cookie, and redirects to the configured return URL.

On the first render after login or F5, the session coordinator refreshes using
the cookie even though C# memory is empty. It receives a JWT and expiration,
validates the JWT with the Hub, and populates the existing authentication state.
Protected content waits for restoration. A missing, expired, or rejected cookie
leaves the app anonymous. Startup transport or configuration errors produce a
restoration error so the app does not mistake them for a request to sign in.

```csharp
var refreshed = await UAuthClient.Flows.RefreshAsync(isAuto: false, ct: cancellationToken);
if (refreshed.IsSuccess)
{
var products = await UAuthClient.Resource.GetAsync<List<Product>>("/api/products", cancellationToken);
}
```

Concurrent refresh callers in one client share a rotation. Cancellation stops the
caller's wait while the shared operation reconciles the response and rotated
cookie. `LogoutAsync()` revokes the refresh chain, expires the cookie, and clears
the in-memory credential and UI state on confirmed success. If logout needs an
access credential, it uses the refresh cookie to obtain one for the Hub's
authenticated logout operation. Already issued JWTs remain valid until expiry
under ordinary PureJwt validation.

The default `IUAuthTokenStore` is scoped and uses C# memory. It stores the JWT
and its expiration, so reloading the WASM runtime discards both. Browser
storage would keep the credential accessible after reload. WASM memory
still offers no protection against XSS. To supply a custom implementation,
register it before the client with
`builder.Services.AddScoped<IUAuthTokenStore, MyTokenStore>()`. Preserve scope
isolation, including per circuit for server-side Blazor. The browser token
transport is available for the BlazorWasm profile.

### Hub and Resource API configuration

Configure the Hub to use PureJwt, retain existing PKCE and antiforgery
middleware, and configure the browser's origin as an allowed Hub client and
return origin using the existing Hub configuration.

```csharp
builder.Services.AddUltimateAuthServer(options =>
{
options.AuthMode = UAuthMode.PureJwt;
options.Token.Issuer = "https://auth.example.com";
options.Token.Audience = "products-api";
options.Token.KeyId = "products-v1";
options.Cryptography.JwtSigningKey = builder.Configuration["UltimateAuth:JwtSigningKey"]
?? throw new InvalidOperationException("JWT signing key is missing.");

options.GrantDelivery.AccessToken.Mode = GrantDeliveryMode.Header;
options.GrantDelivery.AccessToken.HeaderName = "uat";
options.GrantDelivery.AccessToken.HeaderFormat = HeaderTokenFormat.Bearer;
options.GrantDelivery.RefreshToken.Mode = GrantDeliveryMode.Cookie;
options.Cookie.RefreshToken.HttpOnly = true;
options.Cookie.RefreshToken.SecurePolicy = CookieSecurePolicy.Always;
})
.AddUltimateAuthInMemory()
.AddUAuthHub(hub => hub.AllowedClientOrigins.Add("https://app.example.com"));
```

Provision the Hub's production signing key and refresh store. Configure JWT
verification on the Resource API with the Hub's issuer, audience, algorithm and
verification key. PureJwt Resource API authentication reads
`Authorization: Bearer <access token>` by default. For a separate API origin,
allow the app origin in `options.Cors.AllowedOrigins`. The API receives the bearer
header, device ID and application profile. The browser transport omits
cookies and rejects redirects.

Serve all three origins over HTTPS. The credentialed Hub CORS policy must
allow the exact app origin and expose `uat`, `X-UAuth-Access-Expires` and
optionally `X-UAuth-Refresh` and `Retry-After`. The built-in UAuthHub policy
exposes these for the configured header and cookie delivery. Keep the
antiforgery token endpoint and middleware active, and allow its request header
along with `uat`, `X-UDID`, `X-UAuth-ApplicationProfile` and
`X-UAuth-Logout-Mode`. The refresh cookie path must cover both refresh and logout.

A cross-origin deployment can still be same-site. If the app and Hub are
cross-site, configure both the refresh cookie and antiforgery cookie with
`SameSite=None; Secure` using the existing server options. Browsers that block
third-party cookies can still prevent refresh and logout across those sites.
Same-site HTTPS deployment avoids that particular dependency.

PureOpaque continues to use its cookie/session flow with this option disabled.
Hybrid and SemiHybrid retain their existing mode behavior. This browser
integration targets a PureJwt Hub and PureJwt Resource API.

PR #2 covers proactive and expiration-based refresh, request- or 401-triggered
refresh and retry, advanced network recovery, and multi-tab coordination and sync.
Optional access-token possession and sender-constrained tokens remain deferred.

## Next Steps

- [Session Management](/docs/client-sdk/session-management) — Inspect and manage session and device information.
Expand Down
8 changes: 8 additions & 0 deletions docs/content/client-sdk/resource-api-requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,14 @@ The default is:
options.Resource.Credentials = UAuthResourceCredentialsMode.Auto;
```

### PureJwt bearer requests

`UsePureJwtBrowserTokens` attaches the in-memory access token to the configured
HTTPS Resource API origin and omits browser cookies. Requests without a usable
access token return a local 401. Refresh is explicit after startup, so an API
401 reaches the caller without an automatic retry.
[Blazor WebAssembly configuration](/docs/client-sdk/authentication#blazor-webassembly-with-a-purejwt-hub)

### Same-Origin Resource API

When the application and Resource API share an origin:
Expand Down
9 changes: 9 additions & 0 deletions docs/content/configuration/client-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -1229,6 +1229,15 @@ The current client registration validates options when they are resolved, rather

`AutoRefresh.Enabled` should be evaluated with the applicable platform and post-configuration behavior rather than inferred solely from its property initializer.

## PureJwt browser tokens

Set `UsePureJwtBrowserTokens = true` for the BlazorWasm application profile
when the Hub uses PureJwt with a Bearer-formatted `uat` header and an HttpOnly
refresh cookie. This enables startup restoration and bearer authentication for
the configured HTTPS Resource API origin. The existing `AutoRefresh`
coordinator setting applies to the other client flows. See the
[Blazor WebAssembly example](/docs/client-sdk/authentication#blazor-webassembly-with-a-purejwt-hub).

## Next Steps

- **Configuration Overview** — Understand the configuration architecture and source precedence.
Expand Down
6 changes: 6 additions & 0 deletions docs/content/configuration/server-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,12 @@ Use a cryptographically secure, independently generated key in production. Do no

PureJwt does not create authentication sessions, but refresh-token persistence is still required.

For Blazor WebAssembly startup restoration, configure a Bearer-formatted
`uat` access header and an HttpOnly, Secure refresh cookie. The Hub's CORS
policy exposes the access header and expiration metadata to allowed origins.
Use a refresh cookie path that covers both refresh and logout.
[Blazor WebAssembly configuration](/docs/client-sdk/authentication#blazor-webassembly-with-a-purejwt-hub)


### Configure Mode-Specific Behavior

Expand Down
8 changes: 8 additions & 0 deletions docs/content/fundamentals/auth-modes.md
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,14 @@ Changes to user status, permissions, or account existence do not automatically i
Applications should use appropriately short access-token lifetimes and avoid placing sensitive information in JWT payloads.


### Blazor WebAssembly startup

The opt-in PureJwt client uses a scoped in-memory access token and the Hub's
HttpOnly refresh cookie. It restores authentication after a page reload by
rotating the cookie and validating the new access token with the Hub. The
Resource API continues to validate each JWT using its existing PureJwt
configuration. [Blazor WebAssembly configuration](/docs/client-sdk/authentication#blazor-webassembly-with-a-purejwt-hub)

## Choosing a mode

The most useful selection criterion is not the client technology alone, but the authentication guarantees the application requires.
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@ public sealed class LogoutEndpointHandler : ILogoutEndpointHandler
private readonly IAuthRedirectResolver _redirectResolver;
private readonly IRefreshTokenResolver _refreshTokenResolver;
private readonly IPureJwtLogoutService _pureJwtLogout;
private readonly IUAuthCookiePolicyBuilder _cookiePolicy;

public LogoutEndpointHandler(IAuthFlowContextAccessor authContext, IUAuthFlowService flow, IAccessContextFactory accessContextFactory, ISessionApplicationService sessionApplicationService, IUAuthCookieManager cookieManager, IAuthRedirectResolver redirectResolver, IRefreshTokenResolver refreshTokenResolver, IPureJwtLogoutService pureJwtLogout)
: this(authContext, flow, accessContextFactory, sessionApplicationService, cookieManager, redirectResolver, refreshTokenResolver, pureJwtLogout, new UAuthCookiePolicyBuilder())
{
}

public LogoutEndpointHandler(IAuthFlowContextAccessor authContext, IUAuthFlowService flow, IAccessContextFactory accessContextFactory, ISessionApplicationService sessionApplicationService, IUAuthCookieManager cookieManager, IAuthRedirectResolver redirectResolver, IRefreshTokenResolver refreshTokenResolver, IPureJwtLogoutService pureJwtLogout, IUAuthCookiePolicyBuilder cookiePolicy)
{
_authContext = authContext;
_flow = flow;
Expand All @@ -35,6 +41,7 @@ public LogoutEndpointHandler(IAuthFlowContextAccessor authContext, IUAuthFlowSer
_redirectResolver = redirectResolver;
_refreshTokenResolver = refreshTokenResolver;
_pureJwtLogout = pureJwtLogout;
_cookiePolicy = cookiePolicy;
}

public async Task<IResult> LogoutAsync(HttpContext ctx)
Expand All @@ -43,16 +50,26 @@ public async Task<IResult> LogoutAsync(HttpContext ctx)

if (authFlow.EffectiveMode == UAuthMode.PureJwt)
{
if (authFlow.IsAuthenticated)
var cookieDelivery = authFlow.Response.RefreshTokenDelivery.Mode == GrantDeliveryMode.Cookie;
var refreshToken = authFlow.IsAuthenticated || cookieDelivery
? _refreshTokenResolver.Resolve(ctx)
: null;
if (!string.IsNullOrWhiteSpace(refreshToken))
{
var refreshToken = _refreshTokenResolver.Resolve(ctx);

if (!string.IsNullOrWhiteSpace(refreshToken))
var accessDelivery = authFlow.Response.AccessTokenDelivery;
if (!authFlow.IsAuthenticated &&
cookieDelivery &&
accessDelivery.Mode == GrantDeliveryMode.Header &&
accessDelivery.Name is { } accessHeader &&
ctx.Request.Headers.ContainsKey(accessHeader))
{
var revoked = await _pureJwtLogout.LogoutAsync(authFlow, refreshToken, ctx.RequestAborted);
return Results.Unauthorized();
}

if (!revoked)
return Results.Unauthorized();
if (authFlow.IsAuthenticated &&
!await _pureJwtLogout.LogoutAsync(authFlow, refreshToken, ctx.RequestAborted))
{
return Results.Unauthorized();
}
}
}
Expand All @@ -67,7 +84,18 @@ public async Task<IResult> LogoutAsync(HttpContext ctx)
}

DeleteIfCookie(ctx, authFlow.Response.SessionIdDelivery);
DeleteIfCookie(ctx, authFlow.Response.RefreshTokenDelivery);
if (authFlow.EffectiveMode == UAuthMode.PureJwt &&
authFlow.Response.RefreshTokenDelivery.Mode == GrantDeliveryMode.Cookie)
{
var delivery = authFlow.Response.RefreshTokenDelivery;
var deletion = _cookiePolicy.Build(delivery, authFlow, GrantKind.RefreshToken);
deletion.MaxAge = null;
_cookieManager.Delete(ctx, delivery.Cookie!.Name, deletion);
}
else
{
DeleteIfCookie(ctx, authFlow.Response.RefreshTokenDelivery);
}
DeleteIfCookie(ctx, authFlow.Response.AccessTokenDelivery);

var decision = _redirectResolver.ResolveSuccess(authFlow, ctx);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using CodeBeam.UltimateAuth.Core.Contracts;
using CodeBeam.UltimateAuth.Core;
using CodeBeam.UltimateAuth.Core.Domain;
using CodeBeam.UltimateAuth.Core.Options;
using System.Globalization;
using CodeBeam.UltimateAuth.Server.Abstractions;
using CodeBeam.UltimateAuth.Server.Auth;
using CodeBeam.UltimateAuth.Server.Flows;
Expand Down Expand Up @@ -65,6 +68,13 @@ public async Task<IResult> RefreshAsync(HttpContext ctx)
else if (primary == GrantKind.AccessToken && result.AccessToken is not null)
{
_credentialWriter.Write(ctx, GrantKind.AccessToken, result.AccessToken);
if (flow.EffectiveMode == UAuthMode.PureJwt &&
flow.Response.AccessTokenDelivery.Mode == GrantDeliveryMode.Header)
{
ctx.Response.Headers.CacheControl = "no-store";
ctx.Response.Headers["X-UAuth-Access-Expires"] =
result.AccessToken.ExpiresAt.ToString("O", CultureInfo.InvariantCulture);
}
}

if (_refreshPolicy.WriteRefreshToken(flow) && result.RefreshToken is not null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,13 @@ public static IServiceCollection AddUAuthHub(this IServiceCollection services, A
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("X-UAuth-Refresh");

var grants = serverOptions.GrantDelivery;
if ((grants.RefreshToken.Mode ?? grants.Default) == GrantDeliveryMode.Cookie &&
(grants.AccessToken.Mode ?? grants.Default ?? GrantDeliveryMode.Header) == GrantDeliveryMode.Header)
{
policy.WithExposedHeaders(grants.AccessToken.HeaderName ?? "uat", "X-UAuth-Access-Expires", "Retry-After");
}
}
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,7 @@ public interface IUAuthCookieManager
bool TryRead(HttpContext context, string name, out string value);

void Delete(HttpContext context, string name);

void Delete(HttpContext context, string name, CookieOptions options)
=> context.Response.Cookies.Delete(name, options);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,20 @@
@inject IUAuthStateManager StateManager
@inject IUAuthClientBootstrapper Bootstrapper
@inject ISessionCoordinator Coordinator
@inject Microsoft.Extensions.Options.IOptions<CodeBeam.UltimateAuth.Client.Options.UAuthClientOptions> ClientOptions

<CascadingAuthenticationState>
<CascadingValue Value="@StateManager.State" IsFixed="true">
<CascadingValue Name="UAuthRuntimeReady" Value="@_runtimeReady">
@if (RenderMode == UAuthRenderMode.Reactive)
@if (_restorationFailed)
{
<p role="alert">Session restoration failed. Reload the page to try again.</p>
}
else if (ClientOptions.Value.UsePureJwtBrowserTokens && !_runtimeReady)
{
<p role="status">Restoring session…</p>
}
else if (RenderMode == UAuthRenderMode.Reactive)
{
<UAuthScope>
@ChildContent
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Components;
using CodeBeam.UltimateAuth.Client.Errors;
using Microsoft.AspNetCore.Components;
using System.Reflection;

namespace CodeBeam.UltimateAuth.Client.Blazor;
Expand Down Expand Up @@ -28,6 +29,7 @@ public partial class UAuthApp
private bool _initialized;
private bool _coordinatorStarted;
private bool _runtimeReady;
private bool _restorationFailed;

/// <summary>
/// Gets or sets the application content rendered within the UltimateAuth context.
Expand Down Expand Up @@ -130,8 +132,25 @@ protected override async Task OnAfterRenderAsync(bool firstRender)

StateManager.State.RequestRender = () => InvokeAsync(StateHasChanged);

await Bootstrapper.EnsureStartedAsync();
await StateManager.EnsureAsync();
if (ClientOptions.Value.UsePureJwtBrowserTokens)
{
try
{
await Bootstrapper.EnsureStartedAsync();
await Coordinator.RestoreAsync();
}
catch (Exception ex) when (ex is UAuthClientException or Microsoft.JSInterop.JSException)
{
_restorationFailed = true;
StateHasChanged();
return;
}
}
else
{
await Bootstrapper.EnsureStartedAsync();
await StateManager.EnsureAsync();
}

_runtimeReady = true;

Expand Down
Loading
Loading