oauth-server-auth-pages

OAuth Server: Auth Pages, prompt Support and Windows Pass-Through

1. Abstract and motivation

The built-in OAuth server (OAuth2Controller together with an IOAuthService implementation such as the Cheap OAuth Server) shows a few small HTML pages to the user: login, Windows pass-through login, scope consent, error and token display. These pages used to be built by DefaultAuthPageBuilder from hard-coded strings. Changing a page meant re-implementing the whole IAuthPageBuilder, and values from the request were concatenated into the markup without consistent encoding.

This document describes four related changes:

  1. Template-based auth pages. TemplateAuthPageBuilder renders all pages through the embedded HtmlDocGen V2 template engine (MicroTemplateEngine.cs, generated by T4 from https://github.com/KornSW/HtmlDocGen/tree/V2). It includes a new, cleaner design (responsive, dark mode, embedded mode, accessible controls). It is now the default page builder of the Cheap OAuth Server. Single templates can be replaced without re-implementing the builder.
  2. Skipping an empty consent step. If the user has nothing to select (no visible scope that is not read-only), the consent page is no longer shown; the code or token is issued directly.
  3. The OIDC prompt parameter. prompt=none and prompt=consent (and tolerated other values) are supported as an additional, optional query parameter. All existing query parameters keep their meaning.
  4. Automatic Windows pass-through detection. The SSO endpoints no longer require the host to register an authorization policy named WindowsOnly. Whether pass-through is offered is detected automatically and can be overridden with CheapOAuthOptions.EnablePassThrough (Auto / On / Off).

None of these changes is breaking: public signatures are unchanged, every addition is an overload, a new type or a new option with a backward-compatible default, and hosts that registered WindowsOnly behave as before.

2. Positive differentiation

Aspect Former DefaultAuthPageBuilder TemplateAuthPageBuilder Typical alternatives (Razor pages, full IdP products)
Customization Re-implement all of IAuthPageBuilder Replace single named templates; everything else stays Full UI project or theming system
Dependencies None None (engine is embedded as internal source, no NuGet package) Razor runtime compilation, view discovery, static file setup
Encoding Partly manual Interpolation encodes by default; raw must be explicit Usually encodes by default
Look and feel Basic Responsive, dark mode, embedded (iframe) mode, explicit pass-through identity card Product dependent
Footprint Small Small (one class plus template strings) Large
Contract IAuthPageBuilder Same IAuthPageBuilder, unchanged Product specific

Compared to typical IdP products, the Windows pass-through option is detected from the host setup instead of being configured twice. A missing setup shows an error page instead of an unhandled exception.

3. Getting started

3.1 Nothing to do

With the Cheap OAuth Server the new pages are used automatically:

services.AddCheapOAuthServer((options) => {
    options.LoginPageTitle = "My Service";
    options.UseFixedAccounts(("alice", "secret", new string[] { "read" }));
});
  • The login page uses the new design.
  • If the user has nothing to select, the consent page is skipped.
  • prompt=none and prompt=consent are understood.
  • The "Sign in with Windows (Single-Sign-On)" button only appears if the host has Windows authentication configured.

3.2 Enabling Windows pass-through

Register a Windows authentication scheme in the host as usual. EnablePassThrough = Auto (default) detects it:

// Kestrel / HttpSys
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

// IIS / IIS Express: enable Windows authentication in the IIS (web.config / launchSettings.json)

Then the login page offers the SSO button, login_hint=pass-trough (or WINAUTH) is accepted, and /oauth2/sso/authorize challenges the browser for Kerberos/NTLM.

3.3 Switching pass-through explicitly

services.AddCheapOAuthServer((options) => {
    // ...
    options.EnablePassThrough = PassThroughMode.Off; // never offer SSO (e.g. internet-facing hosts)
});

3.4 Asking for silent login or forcing the consent page

GET /oauth2/authorize?response_type=code&client_id=...&redirect_uri=...&state=...&prompt=none
GET /oauth2/authorize?response_type=code&client_id=...&redirect_uri=...&state=...&prompt=consent

4. Advanced usage

4.1 Replacing single templates (corporate branding)

Use case: the login page must show a corporate notice and a different button text, but all other pages and the whole OAuth form handling (hidden fields, PKCE, resource, prompt) must stay untouched.

IDictionary<string, string> templates = new Dictionary<string, string>();
templates.Add(TemplateAuthPageBuilder.LoginTemplateName, @"<u-include template=""Layout"">
    <p class=""ath-prompt"">Internal system - authorized personnel only.</p>
    <form class=""ath-form"" method=""post"" action=""./authorize"" enctype=""application/x-www-form-urlencoded"">
        <div class=""ath-error"" u-if=""_Page.Error"">{{ raw _Page.Error }}</div>
        <label class=""ath-field"">Employee ID
            <input type=""text"" name=""login"" value=""{{ _Page.LoginHint }}"" autocomplete=""username"" autofocus>
        </label>
        <label class=""ath-field"">Password
            <input type=""password"" name=""password"" value="""" autocomplete=""current-password"">
        </label>
        <u-include template=""HiddenFields""></u-include>
        <button class=""ath-btn ath-btn-primary"" type=""submit"">Log on</button>
    </form>
</u-include>");

services.AddSingleton<IAuthPageBuilder>(
    new TemplateAuthPageBuilder("ACME Login", "https://portal.acme.local", "https://acme.local/legal", templates, logo: "https://acme.local/logo.svg")
);
services.AddCheapOAuthServer((options) => { /* ... */ }); // keeps the host-registered page builder

Rules for own templates:

  • Every page with a form must contain exactly one </form>. The controller injects the hidden fields for PKCE, resource and prompt in front of it. Without a form the request fails with an error page instead of silently losing these parameters.
  • Include HiddenFields inside the form, because it carries the OAuth roundtrip values.
  • Use {{ value }} for request values (HTML encoded). Use {{ raw value }} only for _Page.Prompt, _Page.Error and _Page.CustomBody. These fields are HTML fragments by contract of IAuthPageBuilder. The controller encodes user-supplied error text before wrapping it.
  • GetDefaultTemplates() returns a copy of all built-in templates as a starting point.

Note: when a host registers its own builder, the Cheap OAuth decorator (CheapOAuthAuthPageBuilder) is not applied. That decorator adds the client name and redirect host to the consent prompt.

4.2 Non-interactive token refresh in an embedded client (prompt=none)

Use case: a single-page application or a desktop shell renews its session in a hidden iframe and must never show a login page there.

  • With a valid session and nothing to consent, the code is issued directly.
  • Without a session, the client gets error=login_required (plus state).
  • If consent would be needed, the client gets error=consent_required.
  • prompt=none combined with any other value results in invalid_request.
  • prompt=none behaves like the legacy view_mode=3 (pseudo-unattended pass-through): with Windows pass-through available, the user is authenticated silently.
  • For response_type=display (or without a redirect URI) errors are shown as an error page.

4.3 Forcing the consent page (prompt=consent)

Use case: a client wants the user to see and confirm the granted scopes explicitly, even if there is nothing to select. prompt=consent disables the automatic skipping of the consent step.

4.4 Delegation and roundtrips

The prompt value travels like PKCE and resource:

  • as hidden form field oauthPrompt through the HTML forms (not prompt, because the page builders already use that term for the displayed text),
  • as query parameter prompt through the internal ./authorize redirects,
  • as OriginalPrompt in the delegation StateBag. Older serialized state bags without it remain readable.

4.5 Hosts with an existing WindowsOnly policy

Hosts that registered services.AddAuthorization((o) => o.AddPolicy("WindowsOnly", ...)) keep the same behavior. The policy is evaluated exactly as [Authorize(Policy = "WindowsOnly")] did it before, including challenge and forbid results. With EnablePassThrough = Auto, a registered WindowsOnly policy also counts as "pass-through available".

4.6 Hosts without CheapOAuthOptions

Hosts that use AddOAuthServerController() with their own IOAuthService have no CheapOAuthOptions registered. They get PassThroughMode.Auto. To configure the mode anyway, register an options instance: services.AddSingleton(new CheapOAuthOptions { EnablePassThrough = PassThroughMode.Off }).

5. Requirements

Id Requirement Realization
R-01 HtmlDocGen V2 is embedded by T4, without a package reference MicroTemplateEngine.tt generates MicroTemplateEngine.cs (internal types, namespace HtmlDocGen.CopyForAuthTokenHandling) in the net8 project; net10 links it
R-02 All OAuth HTML pages are rendered by the engine TemplateAuthPageBuilder implements all IAuthPageBuilder methods
R-03 Customization without re-implementing the builder Constructor overload with templateOverrides, GetDefaultTemplates(), public template name constants
R-04 New builder is the default (no opt-in) AddCheapOAuthServer registers TemplateAuthPageBuilder via TryAddSingleton (host registrations win)
R-05 DefaultAuthPageBuilder stays available Unchanged public class
R-06 Facelift with cleaner CSS ath-* CSS classes, CSS variables, dark mode, embedded mode, responsive layout
R-07 Pass-through is presented as a clean option Identity card on the pass-through page; secondary button with "or" divider on the login page
R-08 Empty consent step is skipped TryGetScopesWithoutSelection plus IssueAuthorizationResult in GetLogonPage
R-09 prompt=none / prompt=consent supported OAuth2Controller.Prompt.cs, Flow_Entry.cs, Flow_Post.cs
R-10 No breaking change of existing query parameters prompt is an additional optional parameter; view_mode, login_hint, otp, err unchanged
R-11 prompt survives forms, redirects and delegation Hidden field oauthPrompt, 4-argument AppendRoundtripQueryParams overload, StateBag.OriginalPrompt
R-12 No exception if Windows authentication is not configured SSO endpoints are [AllowAnonymous] and use TryEnsurePassThroughIdentity
R-13 SSO button only if pass-through can work IsPassThroughAvailable() (scheme Negotiate / Windows or policy WindowsOnly)
R-14 Explicit override of the detection CheapOAuthOptions.EnablePassThrough (Auto default, On, Off)
R-15 A registered WindowsOnly policy is still respected Evaluated through IPolicyEvaluator
R-16 Untrusted values are encoded Encoding interpolation in templates; error text from the query string is encoded before wrapping

6. Artifacts (bottom-up)

6.1 MicroTemplateEngine.cs (generated, do not edit)

Generated copy of HtmlDocGen V2 with internal types. Relevant features:

  • MemoryTemplateSource, TemplateEngine.Render(templateName, context), TemplateContext.AddSource("_Name", value) (source names start with an underscore),
  • {{ expr }} (encoded) and {{ raw expr }},
  • u-include / u-slot (layouts), u-if / u-else, u-for="item in list".

Re-run the T4 custom tool to update it.

6.2 PassThroughMode and CheapOAuthOptions.EnablePassThrough

public enum PassThroughMode { Auto = 0, On = 1, Off = 2 }
Value Behavior
Auto (default) Offered if an authentication scheme Negotiate or Windows or an authorization policy WindowsOnly is registered
On Always offered; a missing host setup results in an error page (no exception)
Off Never offered: no SSO button, login_hint=pass-trough falls back to the credential form, /sso/authorize shows an error page

6.3 OAuth2Controller pass-through helpers (OAuth2Controller.Helpers.cs)

  • IsPassThroughAvailable() evaluates the mode and the host setup through HttpContext.RequestServices. The controller constructor is unchanged.
  • TryEnsurePassThroughIdentity(viewOpt, out winUserName, out alternativeResult) replaces the former [Authorize(Policy = "WindowsOnly")] on GET and POST /oauth2/sso/authorize:
    1. If pass-through is not available, it returns an error page.
    2. If the WindowsOnly policy is registered, it is authenticated and authorized through IPolicyEvaluator. This results in a challenge or forbid, as before.
    3. Otherwise the request is authenticated with the detected Windows scheme. Without an identity it returns a challenge with that scheme.
    4. If no scheme exists at all (only possible with On), it returns an error page.

6.4 OAuth2Controller prompt and consent helpers (OAuth2Controller.Prompt.cs)

Member Purpose
HasPromptValue(prompt, value) Case-insensitive check within the space-separated prompt
TryValidatePromptParam(prompt, out error) none must stand alone; unknown values are tolerated
TryInjectPromptFormField(ref html, prompt) Adds hidden field oauthPrompt before </form>
AppendRoundtripQueryParams(url, codeChallenge, resource, prompt) Additive overload of the existing 3-argument helper
TryGetScopesWithoutSelection(scopes, out selected) True if no visible, non-read-only scope exists; returns the selected read-only scopes
CreateClientErrorResult(...) OAuth error redirect (error, error_description, state) or error page
IssueAuthorizationResult(...) Shared code/token/display issuance used by the consent POST and the consent skipping

6.5 Authorize flow (Flow_Entry.cs, Flow_Post.cs)

Authentication phase (no session yet):

  • If pass-through is requested but not available:
    • with prompt=none or view_mode=3, the client gets login_required;
    • otherwise the credential form is shown.
  • Otherwise pass-through or the credential form is used as before.
  • With prompt=none, a missing session results in login_required.

Consent phase:

  • Without prompt=consent and with nothing to select, the code or token is issued directly.
  • With prompt=none, a required consent results in consent_required.

POST: oauthPrompt is read from the form and kept in all redirects back to ./authorize.

6.6 TemplateAuthPageBuilder

Constructors:

  • TemplateAuthPageBuilder(title, portalUrl, legalUrl, logo, colors...): same parameters as DefaultAuthPageBuilder.
  • TemplateAuthPageBuilder(title, portalUrl, legalUrl, templateOverrides, logo, colors...): with partial template replacement.

Template names (public constants):

Template name Contents
Head Meta tags and CSS
Layout Page frame with u-slot
HiddenFields OAuth roundtrip fields
Login Credential form
PassThroughLogin Pass-through identity card
Consent Scope list
Error Error page
TokenDisplay Token with copy button
Custom Frame for GetCustomPage

Template model: _Page is an AuthPageModel. It provides:

  • branding: Title, Heading, Logo, PortalUrl, LegalUrl, colors;
  • OAuth fields: ResponseType, State, ClientId, RedirectUri, RequestedScopes, ViewMode, Otp;
  • page contents: Prompt, Error, LoginHint, WinUser, IdentityInitial, Scopes (ScopeModel[]), NoScopes, Message, Token, CustomBody.

ScopeModel exposes Expression, Label, Selected, ReadOnly and PostAsHidden.

6.7 Tests

dotnet/test/AuthTokenHandling.Tests.net10.0:

  • TemplateAuthPageBuilderAndPromptTests: rendering, encoding, template overrides, prompt helpers, roundtrip and consent skipping.
  • PassThroughAvailabilityTests: detection with and without a Negotiate scheme, with a WindowsOnly policy, with an authenticated user, and the explicit On / Off modes.

6.8 Limits

The detection only determines whether the host has Windows authentication configured. It cannot determine in advance whether a particular browser or client can negotiate Kerberos/NTLM. In that case the browser shows its login dialog or the request ends with 401, as before.

Wissen durchsuchen