Agentic UI in Blazor WebAssembly: Sessions, Tokens and Who May Approve a Refund

Agentic UI in WebAssembly: what the browser, web host, agent service and refund tool each hold, check and refuse
On this page

The order desk in Building an Agentic UI with Blazor and .NET 11 ran its Blazor components on the server. The browser held a SignalR connection and nothing else, so the only program that could call the agent service was one I had written. That is why the forged approval in that article needed somebody already inside the network.

Move the same components to Blazor WebAssembly and that protection is gone. The AG-UI client now runs in the browser, and whatever the page can send, anybody with the developer tools open can send too. The agent endpoint has to know who is asking on every request, and a refund has to know who approved it.

I rebuilt the order desk that way and tested it in a pipeline: a WebAssembly client, a web host that keeps the session in a cookie, and an agent service that accepts only a short-lived token for a named person. The components moved to the browser without a change to their markup. The work was in three places the first article did not need: tying each pending approval to the person it was asked of, giving the refund tool the caller’s identity, and deciding what happens when the session ends halfway through a conversation.

The problem

An agentic UI makes authorisation harder than an ordinary web API does, for one reason. The request that moves money is not “refund order O-1001”. It is “here is my answer to the approval you asked for”, and the tool call being approved travels inside that request. A token that proves the request came from a signed-in person says nothing about whether that person was the one asked, or whether they are allowed to approve that amount.

So there are three separate questions, and a design that answers only the first is still open:

  • Who is calling? Authentication, on every request, at a service the browser cannot reach around.
  • Is this approval theirs to give? The approval must have been asked of this person, for this call, and not answered before.
  • May they approve this much? A rule about the person and the amount, enforced where the money moves.

There is also a question about the browser itself. A WebAssembly app is downloaded code. It can be read, changed and replayed, and anything it stores can be stolen by a script that gets into the page. Where the credentials live decides how bad that day is.

Architecture

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
    S["Sign-in page:
lab stand-in for OpenID Connect"] --> H B["Browser: Blazor WebAssembly app,
AGUIChatClient, holds no token"] -- "POST /agent with the session cookie
and an X-Desk-Client header" --> H["Web host: cookie session,
forwards the event stream"] H -- "Bearer token for this person,
valid for two minutes" --> A["Agent service: validates the token,
ties each approval to a person"] A --> T["refund_order tool:
asks who the caller is"] T --> L["Ledger: one refund per order,
with who approved it"] style B fill:#EBF8FF,stroke:#0073BB,stroke-width:2px,color:#004C74 style S fill:#EBF8FF,stroke:#0073BB,stroke-width:2px,color:#004C74 style H fill:#FFF3E0,stroke:#FF9900,stroke-width:2px,color:#232F3E style A fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95 style T fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95 style L fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202

This is the backend-for-frontend arrangement. The browser talks only to the host that served it. The session is an HttpOnly cookie, which the page’s own code cannot read. The host swaps the cookie for a short-lived token addressed to the agent service and passes the event stream back as it arrives. RFC 10017, the IETF’s current best practice for browser-based applications, ranks this pattern first for security and recommends it for business applications and anything that handles personal data. Microsoft’s Blazor guidance for OpenID Connect uses the same shape.

The alternative is to give the browser an access token and let it call the agent service directly. That removes a hop and adds CORS, token storage in the page and token refresh in the page. I did not build it. For an endpoint whose requests can move money, I would want a strong reason to put the token where a script can reach it.

Four columns showing what the browser, the web host, the agent service and the refund tool each hold, check and refuse: the browser holds only an HttpOnly cookie, the web host checks the session and a custom header, the agent service validates the token and the approval owner, and the refund tool applies the approver limit
What each layer holds, what it checks, and how it refuses.
ℹ️
STAND-INS

Three parts of this sample are stand-ins, so that the pipeline needs no account anywhere. Sign-in is a page with two buttons for two invented people, Sam at the order desk and Alex the supervisor. The token is signed with a fake key that sits in the public repository. The model is the scripted one from the first article. The cookie session, the token validation, the approval checks and the tool rule are real code.

The web host

The host has three jobs: serve the WebAssembly app to signed-in people, keep the session, and forward /agent. The cookie setup is where the first decisions are made:

C#26 lines
// The session is a cookie the page's code cannot read. No token is ever given to the browser.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.Cookie.Name = "desk.session";
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Strict;
    options.Cookie.SecurePolicy = lab ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; // the lab runs on http://127.0.0.1
    options.ExpireTimeSpan = TimeSpan.FromMinutes(builder.Configuration.GetValue("DESK_SESSION_MINUTES", 30));
    options.SlidingExpiration = false;
    options.LoginPath = "/signin";

    // A page gets a redirect to the sign-in page. A call from code gets a plain 401 it can act on.
    options.Events.OnRedirectToLogin = context =>
    {
        if (context.Request.Path.StartsWithSegments("/agent") || context.Request.Path.StartsWithSegments("/bff"))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        }
        else
        {
            context.Response.Redirect(context.RedirectUri);
        }

        return Task.CompletedTask;
    };
});

HttpOnly keeps the cookie away from script. SameSite=Strict keeps it off requests that start on another site. The redirect handler matters more than it looks: by default an expired session answers an API call with a redirect to an HTML sign-in page, which a streaming client then tries to parse as events. A call from code should get a plain 401.

The forwarder is thirty lines. It refuses a request that lacks a custom header, builds a token for the signed-in person, and copies the response through without buffering:

C#30 lines
    public static async Task ForwardAsync(HttpContext http, IHttpClientFactory clients, LabTokenIssuer tokens)
    {
        if (!http.Request.Headers.ContainsKey(ClientHeader) || http.Request.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) != true)
        {
            http.Response.StatusCode = StatusCodes.Status400BadRequest;
            return;
        }

        ClaimsPrincipal user = http.User;
        using HttpRequestMessage request = new(HttpMethod.Post, "/agent") { Content = new StreamContent(http.Request.Body) };
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.Issue(
            user.FindFirstValue("sub")!, user.FindFirstValue("name")!, user.FindAll("roles").Select(role => role.Value)));

        // RequestAborted is what carries a Stop click from the browser on to the agent service.
        using HttpResponseMessage response = await clients.CreateClient("agent").SendAsync(request, HttpCompletionOption.ResponseHeadersRead, http.RequestAborted);
        http.Response.StatusCode = (int)response.StatusCode;
        http.Response.ContentType = response.Content.Headers.ContentType?.ToString();
        http.Response.Headers.CacheControl = "no-cache,no-store";
        http.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering();

        await using Stream upstream = await response.Content.ReadAsStreamAsync(http.RequestAborted);
        byte[] buffer = new byte[8192];
        int read;
        while ((read = await upstream.ReadAsync(buffer, http.RequestAborted)) > 0)
        {
            await http.Response.Body.WriteAsync(buffer.AsMemory(0, read), http.RequestAborted);
            await http.Response.Body.FlushAsync(http.RequestAborted);
        }
    }

The header check is the cross-site defence. A page on another site can make a browser send a form post with the victim’s cookie, but it cannot add a custom header without a CORS preflight, and this host allows no other origin. The OWASP cheat sheet describes the technique and is clear that it is one layer: the SameSite attribute is the second.

Two details are easy to get wrong. DisableBuffering and the flush after every read are what keep the answer arriving word by word; without them a proxy can hold the whole response until the run ends. And RequestAborted is passed to every call, because that is how a Stop click in the browser becomes a cancelled run on the agent service.

💡
USE A PROXY LIBRARY IN PRODUCTION

I wrote the forwarder by hand so that every line of the hop is visible. In a real system use YARP, as Microsoft’s Blazor sample does with MapForwarder and a request transform that attaches the token. It handles header rules, timeouts and HTTP/2 that thirty lines do not.

The agent service

The agent service trusts nothing but the token. It validates the signature, issuer, audience and lifetime, and maps the token’s roles to a policy:

C#18 lines
// Every request needs a token made for this service. In the lab the web host signs it with a shared fake
// key; with a real identity provider, set Authority and Audience here and delete the key.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.MapInboundClaims = false;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = LabTokenIssuer.Issuer,
        ValidAudience = LabTokenIssuer.Audience,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["DESK_TOKEN_KEY"] ?? LabTokenIssuer.FakeKey)),
        ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
        NameClaimType = "name",
        RoleClaimType = "roles",
        ClockSkew = TimeSpan.FromSeconds(builder.Configuration.GetValue("DESK_CLOCK_SKEW_SECONDS", 30)),
    };
});
builder.Services.AddAuthorizationBuilder()
    .AddPolicy(Callers.Policy, policy => policy.RequireAuthenticatedUser().RequireRole("agent", "supervisor"));

With a real identity provider the key disappears: set Authority and Audience and the handler fetches the signing keys itself. Pinning ValidAlgorithms is worth keeping either way.

The endpoint is the one from the first article with two additions. It works out who the caller is, and it passes that person to the approval check on the way in and to the approval watcher on the way out:

C#29 lines
app.MapPost("/agent", (
    [FromBody] RunAgentInput input,
    ClaimsPrincipal user,
    IOptions<JsonOptions> jsonOptions,
    IChatClient agent,
    WireLog wire,
    PendingApprovals approvals,
    CancellationToken cancellationToken) =>
{
    JsonSerializerOptions json = jsonOptions.Value.SerializerOptions;
    Caller caller = Callers.From(user);

    // An approval is accepted only from the person it was asked of, and only for the call this server proposed.
    if (verifyResume && approvals.Redeem(input.Resume, caller.Subject) is { } refusal)
    {
        return Results.Problem(refusal.Detail, statusCode: refusal.Status, title: "Approval refused");
    }

    AGUIStreamOptions stream = new AGUIStreamOptions().MapResultAsStateSnapshot(DeskTools.DraftReplyName);
    ChatRequestContext context = input.ToChatRequestContext(json, stream);
    if (input.State is { ValueKind: JsonValueKind.Object } state)
    {
        context.Messages.Insert(0, new ChatMessage(ChatRole.System, ScriptedModel.StatePrefix + state.GetRawText()));
    }

    IAsyncEnumerable<ChatResponseUpdate> updates = agent.GetStreamingResponseAsync(context.Messages, context.ChatOptions, cancellationToken);
    IAsyncEnumerable<BaseEvent> events = approvals.WatchAsync(updates.AsAGUIEventStreamAsync(context, cancellationToken), caller.Subject, cancellationToken);
    return new EventStreamResult(wire.RecordAsync(input, WithoutRawEvents(events, cancellationToken), json, cancellationToken));
}).RequireAuthorization(Callers.Policy);

The approval table now records who each approval was asked of. The order of the checks inside Redeem is the part I got wrong in my head before I wrote the test:

C#32 lines
    public ApprovalRefusal? Redeem(IList<AGUIResume>? resume, string owner)
    {
        foreach (AGUIResume entry in resume ?? [])
        {
            if (!_pending.TryGetValue(entry.InterruptId, out Pending? pending))
            {
                return new(StatusCodes.Status409Conflict, "No approval is pending for this interrupt. It was never asked for, was already answered, or was asked by another server instance.");
            }

            // Checked before the entry is removed: somebody else's request must not use up the approval.
            if (!string.Equals(pending.Owner, owner, StringComparison.Ordinal))
            {
                return new(StatusCodes.Status403Forbidden, "This approval was asked of somebody else.");
            }

            _pending.TryRemove(entry.InterruptId, out _);
            if (pending.Expires < clock.GetUtcNow())
            {
                return new(StatusCodes.Status409Conflict, "The approval request has expired.");
            }

            if (entry.Payload is not { ValueKind: JsonValueKind.Object } payload
                || !payload.TryGetProperty("toolCall", out JsonElement call)
                || !call.TryGetProperty("name", out JsonElement name)
                || ToolCallFingerprint.Of(name.GetString() ?? "", call.TryGetProperty("arguments", out JsonElement arguments) ? arguments : default) != pending.Fingerprint)
            {
                return new(StatusCodes.Status409Conflict, "The tool call in the approval is not the one that was proposed.");
            }
        }

        return null;
    }

The first article removed the pending entry and then compared the call. Add an owner check after the removal and anybody with a valid token can cancel somebody else’s pending approval by answering it wrongly. The owner is compared first, and the entry is removed only when the right person answers.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','signalColor':'#0073BB','signalTextColor':'#0F172A','actorBkg':'#FFF3E0','actorBorder':'#FF9900','actorTextColor':'#232F3E','noteBkgColor':'#FFF8E7','noteBorderColor':'#FF9900','noteTextColor':'#232F3E'}}}%%
sequenceDiagram
    participant B as Browser (Sam)
    participant H as Web host
    participant A as Agent service
    participant L as Ledger
    B->>H: Refund order O-1001 (cookie, header)
    H->>A: Same request, Bearer token for Sam
    A-->>B: Events, run ends on an interrupt
    Note over A: Pending approval stored for Sam
    B->>H: Approve, with the proposed call
    H->>A: Same request, new token for Sam
    Note over A: Owner is Sam, call matches
    A->>L: refund_order as Sam, 42.00
    L-->>A: Refused, above Sam's limit of 40.00
    A-->>B: The agent says a supervisor has to approve

The last rule lives in the tool, because the tool is where money moves. It asks who the caller is at the moment it runs:

C#12 lines
        // The last check before money moves, and the only one that cannot be skipped by a request written
        // by hand: who is asking, and how much that person may approve.
        Caller caller = currentCaller();
        if (!caller.IsKnown)
        {
            return new("refused", order.Id, amount, "No signed-in person is attached to this request.");
        }

        if (amount > caller.RefundLimit)
        {
            return new("refused", order.Id, amount, $"{caller.Name} can approve refunds up to {caller.RefundLimit:0.00}. A supervisor has to approve this one.");
        }

The caller comes from the request’s validated token through a function the service passes in when it builds the pipeline:

C#11 lines
// The tools ask who the caller is at the moment they run. The answer comes from the request's
// validated token; the model has no way to supply it.
builder.Services.AddSingleton<IChatClient>(services =>
{
    IHttpContextAccessor http = services.GetRequiredService<IHttpContextAccessor>();
    return DeskAgent.Create(
        services.GetRequiredService<OrderBook>(),
        services.GetRequiredService<Ledger>(),
        TimeSpan.FromMilliseconds(builder.Configuration.GetValue("DESK_WORD_DELAY_MS", 15)),
        () => Callers.From(http.HttpContext?.User));
});

Nothing about the caller is put into the conversation. The model is not told who the user is or what they may approve, and it has no argument through which it could say. An instruction hidden in an order note can talk the model into proposing a refund; it cannot change who approved it. The ledger entry records the approver, which is the audit trail a refund needs.

⚠️
A LIMIT THE USER CANNOT SEE

The refusal comes back as a tool result, so the run continues and the agent explains it in words. The default approval block still shows “Approved” in green above that explanation, because the label reports the click and not the outcome. In a real desk I would either hide the Approve button when the amount is above the person’s limit or route the request to a supervisor’s queue. Both need the conversation to live on the server, which is the subject of a later article.

The client in the browser

The components, the tool card, the shared-state panel and the Stop button are the files from the first article. What changes is where the chat client points and what happens around it:

C#15 lines
// Same origin, so the browser attaches the session cookie by itself. The header is the cross-site check.
builder.Services.AddScoped(services =>
{
    HttpClient http = new(new SessionHandler(services.GetRequiredService<NavigationManager>()))
    {
        BaseAddress = new Uri(builder.HostEnvironment.BaseAddress),
        Timeout = Timeout.InfiniteTimeSpan,
    };
    http.DefaultRequestHeaders.Add("X-Desk-Client", "1");
    return http;
});

// In the browser the AG-UI client is the page itself. It calls the web host, never the agent service.
builder.Services.AddScoped<IChatClient>(services => new AGUIChatClient(
    new AGUIChatClientOptions(services.GetRequiredService<HttpClient>(), "/agent")));

There is no token code here because there is no token here. The browser attaches the cookie to a same-origin request by itself. When the session has ended, the host answers 401 and one small handler sends the person to sign in:

C#13 lines
public sealed class SessionHandler(NavigationManager navigation) : DelegatingHandler(new HttpClientHandler())
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            navigation.NavigateTo("signin", forceLoad: true);
        }

        return response;
    }
}

One change was forced by publishing. A published WebAssembly app is trimmed, and JSON serialisation that discovers properties by reflection is what trimming breaks first. The shared state and the tool result now use metadata generated at build time:

C#5 lines
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(CaseState))]
[JsonSerializable(typeof(OrderInfo))]
[JsonSerializable(typeof(Me))]
internal sealed partial class DeskJson : JsonSerializerContext;

The host renders nothing on the server. Its root component is a shell that starts the app in the browser with prerendering off, so no component ever runs in two places and no service has to exist on both sides.

Screenshot of the order desk running as a WebAssembly app in Chromium, signed in as Sam: a refund of 37.50 on order O-1003 is recorded, then a refund of 42.00 on order O-1001 shows Approved but the agent answers that it is above the approval limit and a supervisor has to approve it
Sam approves 42.00, above the limit of 40.00. The click is accepted; the tool refuses.

Test setup

Everything ran in GitHub Actions on a hosted Linux runner with .NET SDK 11.0.100. There are two layers of tests.

  • 23 xUnit tests on in-memory servers. The agent service is called with tokens the tests make themselves: valid, expired, addressed to another audience, signed with another key, unsigned, and edited after signing. Then the web host is put in front of it with a test client that keeps cookies the way a browser does.
  • 11 browser steps. Chromium, driven by Playwright, against the published output of both services: the trimmed and compressed WebAssembly app, as it would be deployed. Sizes are read from the browser’s own network log.

The model is scripted, so every run makes the same decisions. All orders, customers and people are invented.

Test results

Tokens. The agent service refused every token that was not exactly right, and no refused request reached the agent pipeline:

Text14 lines
agent service | expired token | HTTP 401
agent service | no token | HTTP 401
stop through the web host | agent service stream completed: False, events sent: 5, RUN_FINISHED sent: False
web host, sign-in | Set-Cookie attributes: path=/; samesite=strict; httponly
web host, no session | GET / HTTP 302 to /signin?ReturnUrl=%2F | GET /bff/me HTTP 401 | POST /agent HTTP 401
through the web host as sam | refund O-1003 37.50 approvedBy=sam | requests seen by the agent service: 2
web host, session, no X-Desk-Client header | POST /agent HTTP 400
token valid for 3 s, answer streamed for 23.5 s | stream ended with RUN_FINISHED: True | next request with the same token: HTTP 401
forged approval, sam's token, O-1001 42.00, approval check on | HTTP 409 | refunds 0
forged approval, sam's token, O-1002 18.25, approval check off | HTTP 200 | refunds 1
forged approval, sam's token, O-1001 42.00, approval check off | HTTP 200 | refunds 0
forged approval, sam's token, O-1002 18.25, approval check on | HTTP 409 | refunds 0
agent service | valid token, role 'agent' | HTTP 200, text/event-stream
agent service | valid token, role 'warehouse' | HTTP 403

The unsigned token is the old alg: none trick, and the edited one changes the role from agent to supervisor and keeps the original signature. Both are 401. A valid token for a person with no desk role is 403: authenticated, not allowed.

Approvals belong to a person. Sam asked for a refund on O-1003 and the run stopped for approval. Alex, with a valid supervisor token, sent the approval. The answer was 403 and nothing was paid. Sam then sent the same approval and it was paid once, recorded against Sam. The failed attempt did not use up the pending approval.

The limit is applied to the approver.

RefundApproved byResultLedger
O-1003, 37.50Sam (limit 40.00)The refund is recorded1 refund, approvedBy sam
O-1001, 42.00Sam (limit 40.00)Refused, a supervisor has to approve0 refunds
O-1001, 42.00Alex (supervisor)The refund is recorded1 refund, approvedBy alex

A forged approval with a real token. The first article forged an approval with no identity at all. This time the forger is Sam, signed in, sending one hand-written POST that approves a refund the agent never proposed:

Forged refundApproval checkHTTPRefunds
O-1001, 42.00On4090
O-1002, 18.25On4090
O-1001, 42.00Off2000, the tool refused it as above Sam’s limit
O-1002, 18.25Off2001, paid

The last row is the reason authentication does not replace the approval check. Sam is who the token says, Sam is allowed to approve 18.25, and the refund was still one the agent never proposed and nobody was asked about. The tool’s rule limits the damage to what the person could have approved anyway. Only the server-side approval table stops it.

Table of ten requests and what happened to each: no session redirects to sign-in, a request without the custom header is 400, six kinds of bad token are 401, a wrong role is 403, an approval answered by another person is 403, forged approvals are 409 with the check on, and with the check off a small forged refund is paid
Every refusal measured in the run, and the two results to design around.

A stream outlives its token. One test issues a token valid for three seconds, with no clock allowance, and asks a question whose answer streams for 23.5 seconds. The stream ran to RUN_FINISHED. The next request with the same token was 401. The token is checked when the request arrives and not again. A two-minute token therefore bounds when a run can start, not how long it can go on, and revoking a person’s access does not end a run that is already streaming. If that matters, put a time limit on the run itself.

In the browser. All eleven steps passed against the published app:

StepWhat was observed
Open the app with no sessionRedirected to the sign-in page; the app shell is not served
First load after sign-in68 responses, 3,002 KiB over the wire, 2,994 KiB of it under /_framework/, Brotli and gzip
Reload59 of 68 responses from the browser cache, 5 KiB over the wire
StreamingWords of the answer on the page at 0.6 s intervals: 7, 11, 15, 19, 23
StopThe agent service’s stream ended after 22 events with no RUN_FINISHED
What the page can readdocument.cookie empty; no request carried an Authorization header; the browser talked to one host
POST without the custom header400
Cookie removed mid-conversationThe next question ended at the sign-in page; the conversation on the page was lost
Sam, then Alex, on O-1001Refused for Sam, paid for Alex, ledger shows who approved each refund

Streaming worked in WebAssembly with no extra setting: the answer grew on the page while the server was still writing it, through the browser’s fetch, the forwarder and back. The browser console showed two errors in the whole run, the 400 and the 401 the tests caused on purpose.

The load times were 1.7 seconds from sign-in to a usable chat with an empty cache and 1.2 seconds on reload. Both were measured on one machine with no network between browser and server, so they show start-up cost and say nothing about a real connection. The 3 MiB is the number to carry to a slow link.

Cost

The price of moving to the browser is a download. The published _framework folder holds 68 files: 13.78 MiB as built, 3.81 MiB as Brotli. A first visit pulled 3.0 MiB. That is less than the whole folder, which also holds source maps and three sets of globalisation data. The largest parts are the .NET runtime (980 KiB compressed) and the core library (627 KiB). The AI components, the AG-UI client and Microsoft.Extensions.AI are small next to them.

What it buys is on the server. The Blazor Server version held a circuit and a WebSocket for every open tab, with the component state in server memory. Here the host holds nothing between requests but a cookie key, and an idle tab costs nothing. I did not measure server memory per user for either version, so treat that as the design difference and not as a number.

The pipeline spends nothing on models or identity providers. The whole run, from restore to the last browser step, took a little over two minutes on a hosted runner.

Production considerations

  • Replace the stand-ins in this order. Sign-in becomes OpenID Connect against your identity provider. The token becomes one the host obtains from that provider for the agent service’s audience. Then delete LabTokenIssuer and the key.
  • The app’s code is public. The framework files are served to anybody; one request with no session returned the script. Everything in the client project ships to the browser. The publish step checks that no server project and no key is in the bundle, and that check is worth keeping.
  • Decide what a lost session costs. Here it costs the conversation, including any approval that was waiting. A 30-minute fixed session is a reasonable default for a desk tool; whether the conversation should survive it is a product decision.
  • Bound the run, not only the token. A stream continued for twenty seconds after its token expired. Give long runs their own time limit and a way to cancel them from the server.
  • Keep the approval table shared. It is in memory on one instance. With two instances an approval asked by one is unknown to the other, and the honest answer is a 409.
  • Log refusals. A 403 on an approval and a 409 on a forged one are the signals somebody is probing the endpoint. Log the subject, the interrupt id and the reason; do not log the token.
  • Rate limits belong on the host. A signed-in browser can now start runs as fast as it can post. None is set in this sample.
⚖️
PERSONAL DATA IN THE BROWSER

Server-side Blazor kept the conversation in server memory. In WebAssembly the whole conversation, including anything the tools return, is in the browser’s memory and is sent back on every request. If tool results contain personal data, the browser is now a place that data is processed, and the device it runs on is in scope for your data protection assessment.

Decision framework

If this is truePreferWhy
Internal tool, stable network, a few hundred usersBlazor Server, as in the first articleNo download, no public endpoint, and the browser cannot call the agent at all
Many users, idle tabs, or a need to scale the web tier without sticky sessionsWebAssembly behind a web host, as hereNo circuit per tab; the host is stateless apart from the cookie key
The agent service is called by other back ends tooWebAssembly behind a web hostThe agent service already validates a token per person; other callers get their own audience
A JavaScript front end or a mobile app must call the agent directlyTokens in the client, with the approval table and the tool rule unchangedNot tested here; RFC 10017 ranks it below a backend for frontend
An approval must be given by a different person than the one who askedNeither as builtThe conversation has to live on the server first

For this order desk I would ship the arrangement in this article. The browser holds nothing worth stealing, the agent service can sit on a private network, and each of the three questions from the start has one place where it is answered: the token handler, the approval table and the refund tool.

Key takeaways

  • The Blazor AI components ran in WebAssembly unchanged, published and trimmed, with streaming and Stop working through a forwarding host.
  • In the browser the page is the AG-UI client. Keep the session in an HttpOnly cookie on the host and give the browser no token.
  • Authentication does not make an approval safe. A signed-in person forged an approval for a refund nobody proposed, and with the server-side check off it was paid.
  • Tie each pending approval to the person it was asked of, and compare the owner before removing the entry.
  • Put the amount rule in the tool, fed by the caller’s validated identity and never by the model.
  • A token is checked when a request starts. A run that is already streaming continues after the token expires.
  • The first visit downloaded 3.0 MiB. A reload downloaded 5 KiB.

A note on testing: everything comes from one pipeline run on 22 November 2026, GitHub Actions run 45003297156: 23 tests passed on in-memory servers and 11 browser steps passed against the published output, on .NET SDK 11.0.100 with the Blazor AI components preview. Sign-in and the token issuer are stand-ins, and no real model was called. I did not build the browser-holds-a-token alternative, use YARP, try ahead-of-time compilation or measure server memory per user. Load times were measured on one machine with no network in between. One preview build was tested and later builds may differ.

References & Further Reading


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.