Security
Authorization runs entirely in the framework, against a session it stores itself; the host's own authentication (cookies, OIDC, whatever ASP.NET Core is configured with) is a separate concern the framework only consumes when told to.
Sessions
Every request resolves to a UserSessionState — SessionId, Language, ThemeMode, TimeZone,
IsAuthenticated, UserId, Roles, Permissions — held by IUserSessionStore (TryGetAsync/SaveAsync/
RemoveAsync/CleanupAsync). The shipped store, UserSessionMemoryStore, keeps sessions in memory, so they are lost
when the process restarts and invisible to any other process. To keep them elsewhere, register a store in the
startup's ConfigureServices:
services.AddUserSessionStore<TStore>()keeps every session inTStore, registered as a singleton.services.AddSignedInUserSessionStore<TStore>()keeps signed-in sessions inTStoreand anonymous ones in memory (UserSessionSplitStore), so a store in a database never sees a crawler, a health check or a visitor who never signs in. A session moves toTStorewith the update that signs it in; an anonymous session is lost when the process stops, which costs its visitor a fresh one.
The framework adds its in-memory store only when none is registered. A store over a database — here the application's
own SqliteSessionStore — is registered for signed-in sessions only:
services.AddSignedInUserSessionStore<SqliteSessionStore>();
Several servers need a shared store and, independently, session affinity (sticky sessions): the live connection and the requests that belong to it must reach the server holding that page's runtime.
The cookie carries a secret; the framework knows the session by its hash. A new session's secret is 32 random bytes
(UISessionSecret), and its SessionId is SHA-256 of the secret as 64 lower-case hex characters — hex, not base64, since
an id is a key in stores and folders that may compare without case. Only the platform's edge, where the cookie is read and
written, ever holds the secret: the store, the runtimes, staged values, the file store and a controller see only the id,
which is no credential, so an id leaked from a store or a log opens no session. A resolver of an application's own that
issues a session takes its id from UserSessionInitData.IssueSessionId(): the platform hands the client the secret behind
that id, and an id a resolver makes up itself is never handed to a client. A log line still writes a short fingerprint of
the id rather than the id, enough to tell one session's lines from another's.
On the web the secret travels in an HttpOnly cookie (SameSite=Lax, Path=/) named UISessionOptions.ClientKey (by
default ne.ui.session. followed by the application's name). Over HTTPS it goes by __Host- and that name, Secure and
with no Domain, so a sibling subdomain can neither set nor shadow it, and the plain name is not read there; a ClientKey
that starts with __Host- or __Secure- itself is refused at startup. Behind a proxy that ends TLS, the host must let
UseForwardedHeaders run before the framework (web hosting): without it every request reads as plain
HTTP and the cookie goes out under the plain name without Secure. Only a page load writes the cookie — the shell render,
or the trade that ends a sign-in (below) — and the SignalR hub reads the same cookie off its negotiate request so both halves
of a page load share one session. The hub only presents a session, never issues one: an attach whose cookie names no session the store holds —
none, an unknown or idle one, one lost to a restart of the in-memory store — is answered with a reload, whose render
writes the new key, since a session the hub issued could never reach the browser and would only be memory held for
nothing. A browser keeping no cookie, or a cross-site iframe the Lax cookie does not reach, cannot run a page with a
controller. ConfigureSessions sets IdleTimeout (default 2 hours — how long a session survives unused),
UnclaimedIdleTimeout (default 5 minutes — how long a session survives that no tab has attached to or written into,
what a crawler or a health check leaves behind), TouchResolution, CleanupInterval (default 5 minutes), ClientKey,
and ClientKeyLifetime:
application.ConfigureSessions(o =>
{
o.IdleTimeout = TimeSpan.FromHours(8);
o.ClientKeyLifetime = TimeSpan.FromDays(30);
});
ClientKeyLifetime is unset by default, and then the cookie lives as long as the browser window: closing it is a
sign-out, whatever IdleTimeout says. Set, the cookie carries that lifetime and is written again on every page
load, so it counts from the last visit — which only means something with a session store that outlives the host,
since the default store is in memory (see above). The presented cookie is written back only as the response's headers go
out, and only while its session still stands with no move to a new id pending, so a load that overlapped another tab's
sign-in never puts back the key the sign-in retired.
TouchResolution (default 1 minute) is how far a session's last-seen time may lag: a page load or an attach that would
change nothing but that time, and move it by less, writes nothing to the store — a store in a database is spared two writes
per page load, and a session may expire up to that much early. It is never more than a tenth of the timeout the session is
under; TimeSpan.Zero writes every time. An open tab's traffic — its commands and its leave checks — touches the last-seen
time by the same rule, so a tab that never reloads does not idle out.
Signing in
A controller changes the session through UIContext, never by writing to a UserSessionState directly (it
is an immutable record):
[UIAllowAnonymous]
internal sealed partial class SignInController(AccountService accounts) : UIControllerBase
{
private string _returnUrl = "/";
[RecursiveMember]
public partial string UserName { get; set; } = string.Empty;
[RecursiveMember]
public partial string Password { get; set; } = string.Empty;
/// <summary>Why the door stayed shut, bound to the password field's validation.</summary>
[RecursiveMember]
public partial UIValidationMessage? Notice { get; set; }
[UICommand]
public async Task<UICommandResult> SignInAsync(CancellationToken cancellationToken)
{
Account? account = accounts.Verify(UserName, Password);
Password = string.Empty;
if (account is null)
{
Notice = UIValidationMessage.Error("Unknown user name or password.");
return UICommandResult.Ok();
}
Notice = null;
await Context.SignInAsync(account.Id, new HashSet<string> { account.Role }, cancellationToken: cancellationToken);
// The session is under a new id already; the page trades for its cookie before it loads the next page.
return UICommandResult.Ok([new NavigateEffect(new UINavigationRequest { Route = _returnUrl })]);
}
}
The view binds the two fields with BindValue and the notice with BindValidation on the password input. The
credentials come from bound fields, not command arguments, and a wrong password is answered on the form and the
command still returns Ok: a thrown UnauthorizedAccessException would not show its message — the runtime
replaces every such refusal with the generic CommandRefusedMessage.
Context.SignInAsync(userId, roles, permissions, cancellationToken)marks the session authenticated, gives it its roles and permissions, and moves it to a new id at once (below).Context.SignOutAsync(cancellationToken)ends the session everywhere — every later command under it is refused, its uploads go, and every other page open under it is sent to sign in.Context.UpdateSessionAsync(update, cancellationToken)applies any other change that must outlive the connection — language, theme, anything else — assession => session with { ... }; a no-op if the session is already gone. Every page of the session holds the new session at once — a new language, theme or colours switches them — and one whose route it no longer passes ends asUpdateUserSessionsAsyncends it, this page once its command has answered.
Sign-in moves the session to a new id at once, as a defence against session fixation. The old id is gone from the store
the moment SignInAsync returns: the signing page goes on under the new one, and every other page still open under the old
id — another tab, or a browser holding a key someone planted — ends silently, while a load presenting it later starts a new
anonymous session. The new key reaches the signing page alone: it is pushed a one-time token ahead of its command's answer
(good once, for a minute, never logged), which its browser trades for the new cookie at POST /_ne/session/key — a same-origin
JSON request that still carries the old session's cookie. Every page load the page starts waits for that trade, and so does
every upload, staged value, selection read and download, so a sign-in no longer has to end in a navigation: the command may
answer in place, or navigate as the sample does. A file the reader uploaded before signing in follows the session to its new id.
Sign in from the page's own command. Called anywhere else — posted work, a job, a call from outside — SignInAsync cannot
tell which page signs in, and throws where another page shares the runtime (UIRuntimeLifetime.PerClient). A sign-in made in
OnInitializeAsync or another hook a page load runs goes out with that load's cookie.
One race is left, a known limit: another tab's page load that read the old id just before a sign-in moved it starts a fresh
anonymous session, whose cookie may reach the browser after the signed-in one and sign it out. Under
UIIdentitySource.Claims the id still rotates at the next page load after the principal signs in.
Returning after sign-in, and signing out
A refused page sends the visitor to the sign-in route with its address — the route and its query, so a deep link's
?id=42 survives — as the returnUrl navigation parameter (see
Refusals below). The sign-in controller reads it once, as it initializes, from the navigation that opened the
page — that is where _returnUrl in the sample above comes from:
protected override Task OnInitializeAsync(CancellationToken cancellationToken)
{
if (Context.Handle.Instance.Navigation.TryGetParameter("returnUrl", out var route) && UIRoutePath.IsLocal(route))
_returnUrl = route;
return Task.CompletedTask;
}
returnUrl is part of the address, so anyone can send a user a sign-in link carrying a value of their choosing,
and the navigation that ends sign-in is a full page load of whatever it names. Accept only a local route — a
path on this site, beginning with a single /; UIRoutePath.IsLocal is that check — and keep a fixed default for
anything else, or the sign-in page becomes an open redirect. The client refuses a NavigateEffect to anything but such a
path as well, so a route that slips through goes nowhere rather than off the site.
Context.SignOutAsync ends the session: it leaves the store with its uploads, and every other page open under it —
another tab, another window — is sent to the sign-in route with its own address as returnUrl (reloaded, where no
sign-in route is configured). The page that signed out keeps running to finish its answer, and still shows what it
showed. End sign-out in a navigation, as both example applications do — the next page load finds no session behind
the cookie, starts a fresh anonymous one (in the language the browser asks for and the default theme), and draws the page for it:
[UICommand]
public async Task<UICommandResult> SignOutAsync(CancellationToken cancellationToken)
{
await Context.SignOutAsync(cancellationToken);
return UICommandResult.Ok([new NavigateEffect(new UINavigationRequest { Route = "/sign-in" })]);
}
Under UIIdentitySource.Claims the host signs people out itself, at an endpoint of its own. A page's connection keeps the
principal it connected with, and a command is checked against the session store, so an open page would go on acting as the
user who signed out: end the UI session there too with HttpContext.EndUISessionAsync(), which ends the session behind the
request's cookie as EndSessionAsync does — its record and uploads go, and every page open under it is sent to sign in.
app.MapPost("/account/sign-out", async (HttpContext http) =>
{
await http.EndUISessionAsync(http.RequestAborted);
await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Results.Redirect("/");
});
Ending and changing sessions from elsewhere
An administrator blocking an account, deleting it or taking a role away acts on sessions that are not the
administrator's own. IUISessions, injected like any service, reaches every session a person is signed in with:
EndUserSessionsAsync(userId, cancellationToken)ends every one of them, as a sign-out ends one — the stored sessions and their uploads go, and every page open under them is sent to sign in at once.EndSessionAsync(sessionId, except, cancellationToken)ends one — a person's other sessions after a password change, for instance;IUserSessionStore.FindByUserAsync(userId)lists them.UpdateUserSessionsAsync(userId, update, cancellationToken)changes every one of them. Commands are checked against the stored session, so a role taken away holds for pages already open from their next command, and for a route from its next load; a page open under a changed session whose route it no longer passes is ended at once and reloaded, and its resolution sends it to sign in or to the forbidden page. A change made straight throughIUserSessionStore, or by another process, reaches open pages at their next command, and at their next value write or item-window read too (RecheckRouteOnActivity, on by default).
A session gone from the store — ended by another process, or purged by the idle sweep — takes its open pages with it too: the sweep ends them as it purges, and a page whose activity refresh finds its session gone is ended then. A page that was never signed in is reloaded rather than sent to sign in.
public async Task BlockAsync(string accountId, CancellationToken cancellationToken)
{
_accounts.SetBlocked(accountId, true);
await _sessions.EndUserSessionsAsync(accountId, cancellationToken);
}
A session store of an application's own implements TryUpdateAsync (read, apply and save as one step, never creating
a session), TouchAsync (the last-seen time and nothing else) and FindByUserAsync: a session is never written back
whole from an earlier read, which would bring back one signed out in another tab meanwhile, or a role revoked meanwhile.
[UIAuthorize] and [UIAllowAnonymous]
Both attach to a view, a controller class, or an individual command method:
[UIAuthorize("Admin,Support", Permissions = "billing.view", RolesMode = UIAccessMode.Any)]
internal sealed partial class BillingController : UIControllerBase { ... }
UIAuthorizeAttribute takes a comma-separated Roles string (constructor) and Permissions (init-only),
plus RolesMode/PermissionsMode (UIAccessMode.Any — the default — or .All). [UIAllowAnonymous] takes
no arguments and lets the route or command resolve with no authenticated session. Both are collected into
UIAccessRules (UIAccessRule.FromAttributes) and evaluated by IUIAuthorizationService.IsAuthorized(session, rules) — every rule must pass, and within a rule roles and permissions are checked independently under their
own mode.
A route with neither attribute is open by default. That suits a public site and is a trap behind a login,
where a forgotten attribute publishes a page — ConfigureSecurity(o => o.DefaultPolicy = UIAuthorizationDefault.Authenticated) inverts the default so the same omission closes a page instead. An
explicit attribute on the view or controller always wins over the policy. Require(rule) on UIRouteDefinitionBuilder
replaces the rules the attributes carry and closes the route: a route that requires a rule refuses an anonymous session
whatever its attributes or the policy say, and only an explicit .AllowAnonymous() on the route opens it again.
Attributes that contradict each other fail the startup. Where both stand, [UIAllowAnonymous] wins, so a
[UIAuthorize] it would quietly open is refused as the routes are built: both on one view, controller or command; one on a
base class, or on the declaration a command overrides; or one on a route's view and the other on its controller. Keep the one
meant. A derived class or an override that declares [UIAllowAnonymous] over its base's [UIAuthorize] opens it on purpose
and stands.
A command with no [UIAuthorize]/[UIAllowAnonymous] of its own follows its route:
IUICommandMetadata.AllowAnonymous is bool?, and null reads UIContext.Route.AllowAnonymous — one
DefaultPolicy therefore governs a page and every command on it together. Only the attributes on the command method
are its own: the controller class's reach its commands through the route, which folds them in, so a route's Require(rule)
or .AllowAnonymous() decides over them for the commands as it does for the page.
Where permissions are read
Route access is checked against the session resolved for that request, so it is always current. A
command is checked against the session store (EnsureCommandAuthorizedAsync), not against
UIHandle.Session — that one is a snapshot taken when the connection attached and refreshed only on the next
attach, so checking it would let a revoked role go on granting access to an already-open tab. A command holds the rules of
the page it runs on as well as its own: [UIAuthorize] on the view and the route's Require(rule) apply to every command
of a page that is not anonymous, so a role the page needs, revoked while it stays open, stops its next command.
The server also refuses what a closed component sends. A command raised on a component that is disabled, loading or
hidden at every width — by a static value or a controller binding, its ancestors' included — is refused as an unauthorised
command is; a value written to such a component or to a read-only input is refused and answered with the server's value, so
the field snaps back — one for a hidden component is also a warning in the log, naming it, since a field kept out of sight (a file
input a button opens) takes no value either (at most RefusalWarningsPerMinute a minute per runtime, the rest at Debug); a choice of a row with CanSelect = false, or a disabled or hidden row, is refused — a select's, a radio group's or a
multi-select's value is such a choice of its options, a single-choice control with ShowClearButton = false refuses null or "" unless already empty, SelectionMode closes SelectedKey/SelectedKeys when that mode does not read them, and a multi-select takes no more keys than its MaxSelected (a free-text tag
no option holds passes) — and so is a key no row of the host holds, for a choice or an event in or of a row, wherever the server
holds the rows: the controller's collection, or rows declared with SetItems, which are gated as the controller's are. Host switches (Draggable, Removable, Renamable) and row abilities (CanDrag, CanRemove, CanRename) close drag moves, removals and inline renames (UITabMenuEntries.Rename and one-shot RenameItemEffect grants open a rename once without leaving a non-renamable control writable); a tree node's DropTarget refuses non-folders, self-drops and ancestor cycles; and a tab strip refuses direct client writes to Order and Pinned and refuses closing a pinned tab (Pinned = true). An address
with fewer row keys than the rows its component stands in is refused as forged. A window is not read for a hidden host (a disabled
or loading one is shown, and gets its rows), and a viewer's query is held to the terms the host offers — its ItemsView's filters
and sorts, and what a package names through IItemsQueryTermsComponent (including AllowSearch for free-text UIItemsQuery.Search) — never a regular expression: the page's write of a query
naming a term it does not offer is refused and answered with the server's value, while a query your controller sets is yours. A
menu's entry event names an entry the menu offers, enabled and shown — never a caption, a rule, a select or an entry opening
others — and an event raised in a template a host picks by the row's item names a row that template draws. A number input's
AllowNegative and AllowDecimals hold the value written, a text input's or area's MaxLength caps its length (counting \r\n as one character), and a splitter's Position stays within [0, 1]. A component holds the page's writes to its own two-way properties to
what it offers (IClientWriteCheckComponent) — a code field's tab size, encoding, line ending and language to its status bar's
choices, a chart's window to a chart that zooms (a sparkline never does) or follows the latest. So is a value outside
an input's bounds — a number's, a slider's, a date's, a time's, a date-time's (compared by instant) or a calendar's Min/Max, static or bound, and a
period's end with them, a range slider's handle past its other end or nearer than its MinDistance, a temporal period's or a calendar's end past or nearer its other than a MinDistance set (a TimeSpan; a date's counts whole days, a time's stays under a day), a slider's value off its Step counted from Min (unset, a step of 1) — and a day a date input or a calendar with MarkedDaysOnly does not offer; a cleared value passes. State an
interaction sets on the client (EnabledWhen, ShownWhen, a panel shown on hover) is not seen by the server, so a property an
interaction writes closes nothing there: a button authored disabled and enabled by EnabledWhen, or a panel authored hidden and
shown by ShownWhen, takes its press whatever the page shows. The server keeps no dialog open or shut either — a press opens a
declared dialog with no round trip — so a dialog's content takes a press whether the dialog is open or not, held only by its own
gates and its ancestors'. A component a command reveals is one whose visibility is bound
to the controller, which the server reads. These guard against a stale or forged page, not in place
of a check: permissions, and what a rule on the page only shows, still belong in the command or the setter — or in a gate
bound to the controller, which the server reads.
A row reaches the browser with what its host reads. A row's item is sent with every property its templates, filters,
sorts and abilities read — the whole item where the host cannot know (a chart, a layered graph, ReadsWholeItems()) — and the
DataGrid with its columns' and templates' paths. What a reader must not see stays out of the row model, not out of the template.
UISecurityOptions
Set through application.ConfigureSecurity(configure):
DefaultPolicy—UIAuthorizationDefault.Anonymous(default) or.Authenticated; see above.SignInRoute/ForbiddenRoute— set byUIApplicationBuilder.SignInView<TView>(route)/ForbiddenView<TView>(route)(each with a controller-backed overload), which also register the route anonymous, since a page that explains a refusal must not be able to refuse anyone itself.IdentitySource—UIIdentitySource.Session(default: the application signs users in itself, and anyClaimsPrincipalthe host supplies is ignored) or.Claims(the host'sClaimsPrincipal, viaHttpContext.Useron the web, is authoritative in both directions, mapped byIUserClaimsMapper.Map). The framework consumes a principal and never authenticates — the host ownsAddAuthentication(); the web setup, middleware order included, is in web hosting.PermissionClaimType— the claim type permissions are read from underClaims(default"permission"); roles need no equivalent, since aClaimsIdentityalready declares its ownRoleClaimType.RecheckRouteOnActivity— on by default: an open page's value writes and item-window reads re-check its route's rules against the session as stored, as its commands do, so a role revoked straight in the store or by another process ends the page there too. It reads the session the touch reads anyway, at most once per open page eachTouchResolution, so it costs a check of the route's rules, never a store read; the page then goes back to its own address, whose load refuses it.RefusalWarningsPerMinute— how many refusals a page's runtime writes to the log as warnings each minute (default 10); past it they go atDebug, so a page sending forged writes in a loop cannot flood the log. Zero or less writes every one atDebug. An unknown event id, or a write to an address no binding of the page takes, is a refusal atDebugtoo.
application.ConfigureSecurity(o =>
{
o.DefaultPolicy = UIAuthorizationDefault.Authenticated;
});
application.SignInView<SignInView, SignInController>("/sign-in");
application.ForbiddenView<ForbiddenView>("/forbidden");
Refusals
Two exceptions mean two different things, and are routed differently by the built-in resolve-exception handler:
- No identity yet — a plain
UnauthorizedAccessException— goes toSecurity.SignInRoutewith the refused route as thereturnUrlnavigation parameter. - An authenticated session that fails the rules —
UIForbiddenAccessException— goes toSecurity.ForbiddenRoutewith the refused route asdeniedUrl, falling back to the sign-in route when no forbidden view is registered.EnsureCommandAuthorizedAsyncthrows the former when the store holds no live session, and the latter when the session fails an access rule.
With neither SignInView nor ForbiddenView configured, the exception propagates unchanged rather than
being redirected.
A command's refusal is not a navigation. The redirects above belong to view resolution — opening a page. A
command that fails its [UIAuthorize], or any command that throws, leaves the page where it is: the runtime
turns the failure into a notification (CommandRefusedMessage for a refusal, CommandFailedMessage for the
rest, see ConfigureErrorHandling), and the user sees a toast, not a sign-in page. So the attribute is the
whole of a per-command role check; there is no need to re-test the role by hand inside the command to get a
graceful answer.
IUIAuthorizationService and IUserClaimsMapper
IUIAuthorizationService.IsAuthorized(session, rules)/IsAuthorized(session, rule) is the seam evaluating
access rules — the shipped StandardAuthorizationService checks roles and permissions independently, each
under its own Any/All mode, and every rule in a list must pass. IUserClaimsMapper.Map(ClaimsPrincipal)
turns the host's principal into a UserClaimsIdentity (IsAuthenticated, UserId, Roles, Permissions)
under UIIdentitySource.Claims — replace the registered implementation to map an application's own claim
shapes. Both are ordinary DI services, replaceable with services.AddSingleton<IUIAuthorizationService, MyAuthorizationService>().
The web host's own authorization
WebEndpointOptions.RequireAuthorization and AuthorizationPolicy gate the framework's two ASP.NET Core
endpoints — the SignalR hub and the catch-all shell route — with ordinary ASP.NET Core authorization,
independent of everything above:
services.Configure<WebEndpointOptions>(o =>
{
o.RequireAuthorization = true;
o.AuthorizationPolicy = "MyPolicy";
});
This is the host deciding who may reach the framework at all (useful behind a reverse proxy or a corporate
SSO gate); the framework's own [UIAuthorize]/DefaultPolicy machinery above still runs independently on top
of whatever gets through.
An address bound to a link, a picture or an icon is checked where it is written — as the page renders and again as a push
patches it (WebUrlSafety, and its twin in the page's script): a link keeps a relative, http, https, mailto or tel
address, a picture a path of this site — absolute, or relative to the page (img/x.png) —, http(s) or a data:image/… one,
and anything else — javascript: among them — is dropped; an icon's picture also names a folder or a scheme, since a bare word is a
glyph's name. A return address a command navigates to is a path of this site with no control character anywhere. An address is judged as the browser reads it: the controls and spaces at its ends and every tab and line break inside
fall away first, so /\host, /<tab>/host or //host behind a control character, which the browser loads from another site,
is never taken for a path of this one. A link that leaves the application opens in a new tab with rel="noopener noreferrer".
Content and downloads are always served inert — a Content-Security-Policy
that runs nothing, and HTML, XML or SVG sent as an attachment — so a file a user uploaded cannot run script under the
application's origin when it is opened directly (files). A script, a stylesheet, a WebAssembly module or a type
that does not parse goes out as application/octet-stream, so a page never runs an upload as its <script src> either — which
a host's script-src 'self' would let through. The options' InlinePassiveContent (off by default) relaxes only a type that
runs nothing (a PDF, a raster image, plain text, audio, video), shown inline without the policy.
A page may be framed by its own origin only. Every page goes out with X-Frame-Options: SAMEORIGIN (unless the host
sent one of its own) and Content-Security-Policy: frame-ancestors 'self', appended beside any policy the host sends, never
over it: a sibling site framing a signed-in page could steer the reader's presses. An application framed by another site
names its framers, sent as the policy alone, or turns the rule off and leaves framing to its own headers:
services.Configure<WebEndpointOptions>(o => o.FrameAncestors = "'self' https://partner.example");
A page loads only as a document. A request for a page whose Sec-Fetch-Dest says it is anything else — an <img>, a
script, a fetch — and a cross-site frame's while only the page's own origin may frame it, is answered 404 before any
session, filter or hook runs: another site's content naming a page would otherwise run its navigation hooks as whoever views
it. A request without the header (an older browser, a test client) is taken as a document. An application's own service
worker that precaches pages with fetch(url) caches that 404; let it pass a navigation's own request on instead.