{ ["message"] = "Recovery code accepted" };
if (e.In.Headers.TryGetValue("Set-Cookie", out var cookie))
e.Out.Headers["Set-Cookie"] = cookie;
return Task.CompletedTask;
}
// Failed — re-render form with error
var mfaState = body.TryGetValue("mfa_state", out var st) ? st?.ToString() ?? "" : "";
var errorDesc = body.TryGetValue("error_description", out var ed)
? ed?.ToString() : "Invalid recovery code";
var cardContent = BuildRecoveryForm(mfaRecoveryPath, mfaPath, mfaState, opts, errorDesc);
e.Out = new Message();
e.Out.Body = IdentityPageTemplates.WrapPage("Recovery Code", cardContent, opts);
e.Out.Headers[HttpHeaders.ResponseContentType] = "text/html; charset=utf-8";
e.Out.Headers[HttpHeaders.ResponseCode] = 200;
return Task.CompletedTask;
}
// ── HTML builders ──
private static string BuildTotpForm(
string mfaPath, string mfaState, bool hasRecovery,
IdentityTransportOptions opts, string? error = null)
{
var errorHtml = string.IsNullOrEmpty(error)
? ""
: $"""{WebUtility.HtmlEncode(error)}
""";
// B3 §4: mfa_state lives in the __Host-redb.identity.mfa cookie, never in URLs.
var recoveryLink = hasRecovery
? $"""Use a recovery code
"""
: "";
_ = mfaState; // state travels in the cookie; kept in signature for form re-render on error
return $$"""
Verification Code
Enter the 6-digit code from your authenticator app
{{errorHtml}}
{{recoveryLink}}
""";
}
private static string BuildRecoveryForm(
string mfaRecoveryPath, string mfaPath, string mfaState,
IdentityTransportOptions opts, string? error = null)
{
var errorHtml = string.IsNullOrEmpty(error)
? ""
: $"""{WebUtility.HtmlEncode(error)}
""";
// B3 §4: no mfa_state in URLs / form inputs — cookie carries it.
_ = mfaState;
return $$"""
Recovery Code
Enter one of your recovery codes
{{errorHtml}}
Back to authenticator code
""";
}
///
/// Builds a method-selector view: lets the user pick TOTP / SMS / Email.
/// TOTP is verified inline; SMS/Email triggers an AJAX call to /mfa/challenge
/// which sends the OTP and returns a new mfa_state ; the form then swaps to OTP entry.
///
private static string BuildMethodSelector(
string mfaPath, string mfaState, string[] methods, bool hasRecovery,
IdentityTransportOptions opts)
{
var primary = opts.Branding.PrimaryColor;
var hasSms = methods.Contains("sms");
var hasEmail = methods.Contains("email");
var hasTotp = methods.Contains("totp");
var buttons = new System.Text.StringBuilder();
if (hasTotp)
{
buttons.Append($"""Authenticator app (TOTP) """);
}
if (hasSms)
{
buttons.Append($"""Send code via SMS """);
}
if (hasEmail)
{
buttons.Append($"""Send code via Email """);
}
// B3 §4: no mfa_state in URLs — the __Host-redb.identity.mfa cookie carries it.
var recoveryLink = hasRecovery
? $"""Use a recovery code
"""
: "";
var challengePath = mfaPath.TrimEnd('/') + "/challenge";
var encodedMfaPath = WebUtility.HtmlEncode(mfaPath);
var encodedChallengePath = WebUtility.HtmlEncode(challengePath);
_ = mfaState; // retained in signature for future form re-render; state travels via cookie
return $$"""
Verification Required
Choose a verification method
{{buttons}}
{{recoveryLink}}
""";
}
///
/// Legacy-compat helper: extracts mfa_state from the raw query string. Used
/// only as a fallback when the cookie is absent (e.g. direct link during rollout).
///
private static string? ExtractMfaStateFromQuery(IExchange e)
{
var query = e.In.GetHeader(HttpHeaders.Query);
if (string.IsNullOrEmpty(query)) return null;
foreach (var part in query.Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var eqIdx = part.IndexOf('=');
if (eqIdx <= 0) continue;
if (part[..eqIdx] == "mfa_state")
return Uri.UnescapeDataString(part[(eqIdx + 1)..]);
}
return null;
}
}
Path: redb-identity/src/redb.Identity.Http/Processors/ScimHttpProcessors.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/ScimHttpProcessors.cs
----
using System.Text.Json;
using redb.Identity.Contracts.Scim;
using redb.Identity.Contracts.Serialization;
using redb.Route.Abstractions;
namespace redb.Identity.Http.Processors;
///
/// SCIM-specific HTTP processors for /scim/v2/* routes.
/// Handles error-to-status mapping, content type, and response serialization.
///
internal static class ScimHttpProcessors
{
///
/// Maps SCIM response body to appropriate HTTP status codes.
/// Runs AFTER RedbHttpController (which serializes to byte[] and sets 200),
/// so must parse the serialized JSON to detect ScimError responses.
/// Also handles custom scim.ResponseCode/Location headers set by processors.
///
internal static Task MapScimResponseToHttpStatus(IExchange exchange, CancellationToken ct)
{
var msg = exchange.HasOut ? exchange.Out! : exchange.In;
var body = msg.Body;
// Check for processor-set custom response code (e.g. 201 Created)
if (exchange.In.Headers.TryGetValue("scim.ResponseCode", out var customCode) && customCode is int code)
{
msg.Headers["redbHttp.ResponseCode"] = code;
if (exchange.In.Headers.TryGetValue("scim.Location", out var loc) && loc is string location)
msg.Headers["Location"] = location;
if (exchange.In.Headers.TryGetValue("scim.ETag", out var etagCustom) && etagCustom is string etagVal)
msg.Headers["ETag"] = etagVal;
if (!exchange.HasOut)
exchange.Out = msg;
return Task.CompletedTask;
}
// RedbHttpController serializes results to byte[]; parse to detect ScimError
if (body is byte[] jsonBytes && jsonBytes.Length > 2)
{
try
{
using var doc = JsonDocument.Parse(jsonBytes);
if (doc.RootElement.TryGetProperty("status", out var statusEl)
&& doc.RootElement.TryGetProperty("schemas", out _))
{
var statusStr = statusEl.GetString();
if (statusStr is not null && int.TryParse(statusStr, out var errCode) && errCode >= 400)
{
msg.Headers["redbHttp.ResponseCode"] = errCode;
// Pipeline merges Out→In between steps and restores lastOut at the end.
// If we only set the header on In (post-merge), lastOut retains the
// original 200 from WriteResult. Force-set Out so Pipeline tracks our override.
if (!exchange.HasOut)
exchange.Out = msg;
}
}
}
catch (JsonException) { /* not valid JSON — leave default status */ }
}
else if (body is ScimError err && int.TryParse(err.Status, out var status))
{
msg.Headers["redbHttp.ResponseCode"] = status;
if (!exchange.HasOut)
exchange.Out = msg;
}
// Propagate ETag header for normal (200 OK) responses.
// Must set exchange.Out so PipelineProcessor captures it as lastOut;
// otherwise the restored Out from RedbHttpController won't have the ETag.
if (exchange.In.Headers.TryGetValue("scim.ETag", out var etag) && etag is string etagStr
&& !msg.Headers.ContainsKey("ETag"))
{
msg.Headers["ETag"] = etagStr;
if (!exchange.HasOut)
exchange.Out = msg;
}
return Task.CompletedTask;
}
///
/// Sets Content-Type: application/scim+json on the response
/// and serializes the body to JSON if it's not already a string/byte[].
///
internal static Task SerializeScimJsonResponse(IExchange exchange, CancellationToken ct)
{
var msg = exchange.HasOut ? exchange.Out! : exchange.In;
// Set the transport-agnostic Message.ContentType so non-HTTP consumers
// (RabbitMQProducer, Kafka, …) carry the SCIM media type natively.
// The HTTP header mirror is kept for HttpConsumer override semantics.
msg.ContentType = ScimConstants.MediaType;
msg.Headers["redbHttp.ResponseContentType"] = ScimConstants.MediaType;
if (msg.Body is not null and not string and not byte[])
{
// Go through the IMessageSerializer facade rather than the raw static options
// so the wire format is observably identical to what external callers get
// when they resolve "application/scim+json" from IDataFormatRegistry.
// Serialize() returns byte[]; HttpProducer accepts that as payload.
// SCIM wire serialization (RFC 7644 §3) — locked options live in Contracts so
// the HTTP facade can serialize without taking a project-reference on Core.
msg.Body = JsonSerializer.SerializeToUtf8Bytes(msg.Body, IdentityWireProfiles.ScimOptions);
}
return Task.CompletedTask;
}
///
/// Strips the SCIM base path prefix (/scim/v2 ) from the request path
/// so that dispatch
/// sees controller-relative paths like /Users/123 .
///
internal static Task StripScimPrefix(IExchange exchange, CancellationToken ct)
{
var path = exchange.In.GetHeader("redbHttp.Path");
if (path is not null)
{
const string prefix = "/scim/v2";
if (path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
exchange.In.Headers["redbHttp.Path"] = path[prefix.Length..];
}
return Task.CompletedTask;
}
}
Path: redb-identity/src/redb.Identity.Http/Processors/SessionCookieProcessors.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Processors/SessionCookieProcessors.cs
----
using redb.Identity.Http.Security;
using redb.Route.Abstractions;
using redb.Route.Http;
using redb.Identity.Contracts.Configuration;
namespace redb.Identity.Http.Processors;
///
/// HTTP processors for reading and writing encrypted session cookies.
/// The cookie contains an encrypted ticket with userId + username (self-contained, no DB lookup).
///
internal static class SessionCookieProcessors
{
internal const string DefaultCookieName = "redb.identity.session";
internal const string SessionUserIdHeader = "session_user_id";
internal const string SessionUsernameHeader = "session_username";
internal const string SessionIdHeader = "session_id";
// Re-authentication marker (prompt=login / max_age). A DataProtection-signed cookie carrying
// the instant re-auth was forced; on the return trip the authorize handler compares it to the
// session's auth_time to decide whether the End-User re-authenticated. See HandleReauthCookie.
internal const string ReauthCookieName = "redb.identity.reauth";
internal const string ReauthMarkedSidHeader = "reauth_marked_sid"; // in: session id active when re-auth was forced (0 = none)
internal const string ReauthSetProperty = "reauth_set"; // out: exchange prop = session id to mark (long)
internal const string ReauthClearProperty = "reauth_clear"; // out: exchange prop = true
private static readonly TimeSpan ReauthMarkerMaxAge = TimeSpan.FromMinutes(10);
// POST /connect/authorize carries the request in the form body, not in the query string. The
// body is replaced by the authorize response before RedirectToLogin and RedirectToConsent run,
// so the form is kept here, encoded as a query, for the return trip.
internal const string AuthorizeFormQueryProperty = "identity:authorize-form-query";
///
/// Keeps the parameters of a form-encoded authorization request (OIDC Core 3.1.2.1, POST) as a
/// query string, so the login and consent pages return to GET /connect/authorize with
/// the same request. Runs after .
///
internal static Task CaptureAuthorizeForm(IExchange e, CancellationToken ct)
{
if (e.In.Body is IDictionary form && form.Count > 0)
{
e.Properties[AuthorizeFormQueryProperty] = string.Join("&", form.Select(kv =>
kv.Value is null
? Uri.EscapeDataString(kv.Key)
: $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value.ToString() ?? string.Empty)}"));
}
return Task.CompletedTask;
}
///
/// The authorization request the browser made, as a local path: the form of a POST request,
/// otherwise the query string of a GET request.
///
private static string OriginalAuthorizeUrl(IExchange e)
{
var path = e.In.GetHeader(HttpHeaders.Path) ?? "/connect/authorize";
var query = e.Properties.TryGetValue(AuthorizeFormQueryProperty, out var fq) && fq is string formQuery && formQuery.Length > 0
? formQuery
: e.In.GetHeader(HttpHeaders.Query);
return string.IsNullOrEmpty(query) ? path : $"{path}?{query}";
}
///
/// Reads the session cookie from the HTTP request, decrypts it, and sets
/// session_user_id and session_username headers on the exchange.
/// Must run before routing to the authorize endpoint. Tries both the bare name
/// and the __Host- prefixed variant so deployments can flip
/// without a forced re-login window.
///
internal static Task ReadSessionCookie(
IExchange e, CancellationToken ct,
SessionTicketService ticketService, TimeSpan maxAge,
string bareCookieName)
{
var cookieHeader = e.In.GetHeader("Cookie");
if (string.IsNullOrEmpty(cookieHeader))
return Task.CompletedTask;
// Re-auth marker (prompt=login / max_age): decode it up-front so the authorize handler can
// tell whether the End-User re-authenticated since it forced re-auth. Independent of the
// session cookie (it must survive the new session that /login creates).
var (reauthPrefixed, reauthBare) = IdentityCookieFormatter.Candidates(ReauthCookieName);
var reauthValue = ParseCookieValue(cookieHeader, reauthPrefixed)
?? ParseCookieValue(cookieHeader, reauthBare);
if (reauthValue is not null)
{
var reauth = ticketService.UnprotectReauth(reauthValue, ReauthMarkerMaxAge);
if (reauth.HasValue)
e.In.Headers[ReauthMarkedSidHeader] = reauth.Value.MarkedSessionId;
}
var (prefixed, bare) = IdentityCookieFormatter.Candidates(bareCookieName);
var ticketValue = ParseCookieValue(cookieHeader, prefixed)
?? ParseCookieValue(cookieHeader, bare);
if (ticketValue is null)
return Task.CompletedTask;
var ticket = ticketService.Unprotect(ticketValue, maxAge);
if (ticket is null)
return Task.CompletedTask;
e.In.Headers[SessionUserIdHeader] = ticket.UserId;
e.In.Headers[SessionUsernameHeader] = ticket.Username;
if (ticket.SessionId > 0)
e.In.Headers[SessionIdHeader] = ticket.SessionId;
return Task.CompletedTask;
}
///
/// Writes / clears the re-authentication marker cookie on the authorize response, driven by
/// exchange properties the OpenIddict authorize handler set:
///
/// (session id, 0 = none) → the handler is forcing re-auth
/// (prompt=login or max_age); mint a signed redb.identity.reauth cookie binding the
/// currently-active session so the return trip can prove the End-User signed in again.
/// → re-auth was satisfied; consume the marker (expire
/// the cookie) so a stale marker can never satisfy a LATER prompt=login (would be a bypass).
///
/// Runs after the redirect processors so it appends its Set-Cookie to the final response (login
/// redirect, consent redirect, or the success code redirect).
///
internal static Task HandleReauthCookie(
IExchange e, CancellationToken ct,
SessionTicketService ticketService,
bool secure, CookieSameSiteMode sameSite, bool useHostPrefix)
{
string? setCookie = null;
if (e.Properties.TryGetValue(ReauthSetProperty, out var rs) && rs is long markedSessionId)
{
var marker = ticketService.ProtectReauth(markedSessionId);
setCookie = IdentityCookieFormatter.Build(
ReauthCookieName, marker,
maxAgeSeconds: (int)ReauthMarkerMaxAge.TotalSeconds,
secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix);
}
else if (e.Properties.TryGetValue(ReauthClearProperty, out var rc) && rc is true)
{
setCookie = IdentityCookieFormatter.Build(
ReauthCookieName, value: string.Empty,
maxAgeSeconds: 0,
secure: secure, sameSite: sameSite, useHostPrefix: useHostPrefix);
}
if (setCookie is null)
return Task.CompletedTask;
var msg = e.HasOut ? e.Out! : e.In;
// Added, not assigned. No response on this route carries another cookie today, but losing this
// one to a later assignment is the bypass named above, so it must never depend on that.
IdentityCookieFormatter.AddSetCookie(msg.Headers, setCookie);
return Task.CompletedTask;
}
///
/// Writes the session cookie to the HTTP response after successful login.
/// Reads userId/username from the current message body (In or Out, depending on pipeline merge state).
///
internal static Task WriteSessionCookie(
IExchange e, CancellationToken ct,
SessionTicketService ticketService, TimeSpan maxAge,
bool secure, string bareCookieName,
CookieSameSiteMode sameSite, bool useHostPrefix)
{
// After PipelineProcessor merges Out→In, the body is on In; if Out is present, use it.
var msg = e.HasOut ? (IMessage)e.Out! : e.In;
var body = msg.Body as IDictionary;
if (body is null)
return Task.CompletedTask;
if (body.TryGetValue("success", out var s) && s is true &&
body.TryGetValue("userId", out var uid) && uid is long userId &&
body.TryGetValue("username", out var uname) && uname is string username)
{
var sessionId = body.TryGetValue("sessionId", out var sid) && sid is long sId ? sId : 0L;
var ticket = ticketService.Protect(userId, sessionId, username);
IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build(
bareCookieName,
ticket,
maxAgeSeconds: (int)maxAge.TotalSeconds,
secure: secure,
sameSite: sameSite,
useHostPrefix: useHostPrefix));
}
return Task.CompletedTask;
}
///
/// Clears the session cookie (for logout). Mirrors the flags used by
/// so the browser actually deletes the matching cookie.
///
internal static Task ClearSessionCookie(IExchange e, CancellationToken ct,
bool secure, string bareCookieName,
CookieSameSiteMode sameSite, bool useHostPrefix)
{
var msg = e.Out ?? e.In;
IdentityCookieFormatter.AddSetCookie(msg.Headers, IdentityCookieFormatter.Build(
bareCookieName,
value: string.Empty,
maxAgeSeconds: 0,
secure: secure,
sameSite: sameSite,
useHostPrefix: useHostPrefix));
return Task.CompletedTask;
}
///
/// Redirects to the login page when the authorize endpoint returns login_required .
/// Constructs /login?returnUrl=<original-authorize-url> .
///
internal static Task RedirectToLogin(
IExchange e, CancellationToken ct, string loginPath)
{
// OIDC §3.1.2.6: prompt=none MUST NOT trigger any interactive UI. When the
// OpenIddict handler rejected with login_required for that reason, it sets the
// `prompt_none` flag — let the standard redirect-to-redirect_uri error response
// (already wired by HandleRedirectResponse) flow through unchanged.
if (e.Properties.TryGetValue("prompt_none", out var pn) && pn is true)
return Task.CompletedTask;
// PipelineProcessor merges Out→In and nulls Out between steps, so the body
// produced by the upstream OpenIddict processor lives on In by the time we run.
var rawBody = e.HasOut ? e.Out!.Body : e.In.Body;
if (rawBody is not IDictionary body)
return Task.CompletedTask;
if (!body.TryGetValue("error", out var err) || err?.ToString() != "login_required")
return Task.CompletedTask;
var originalUrl = OriginalAuthorizeUrl(e);
var redirectUrl = $"{loginPath}?returnUrl={Uri.EscapeDataString(originalUrl)}";
var msg = e.HasOut ? e.Out! : e.In;
// Empty byte[] body (not null) so HttpConsumer.WriteResponse enters the
// header-copying branch and emits the Location header for the 302.
msg.Body = Array.Empty();
msg.Headers[HttpHeaders.ResponseCode] = 302;
msg.Headers["Location"] = redirectUrl;
return Task.CompletedTask;
}
///
/// Redirects to the consent page when the authorize endpoint returns consent_required .
/// The consent parameters travel in a server-signed ticket (/consent?ct=… ), never as
/// query fields: the page used to render app_name /scopes from the URL, so a
/// crafted link could show the operator's trusted UI attributing an attacker's client to a
/// familiar name ( ).
///
internal static Task RedirectToConsent(
IExchange e, CancellationToken ct, string consentPath, SessionTicketService ticketService)
{
// Same merge consideration as RedirectToLogin: body may live on In after Out→In merge.
var rawBody = e.HasOut ? e.Out!.Body : e.In.Body;
if (rawBody is not IDictionary body)
return Task.CompletedTask;
if (!body.TryGetValue("error", out var err) || err?.ToString() != "consent_required")
return Task.CompletedTask;
// Read consent details from exchange properties (set by HandleAuthorizationRequestHandler)
var clientId = e.Properties.TryGetValue("consent_client_id", out var cid) ? cid?.ToString() : null;
var appName = e.Properties.TryGetValue("consent_app_name", out var an) ? an?.ToString() : null;
var scopes = e.Properties.TryGetValue("consent_scopes", out var sc) ? sc?.ToString() : null;
var userId = e.Properties.TryGetValue("consent_user_id", out var uid) ? uid?.ToString() : null;
if (clientId is null) return Task.CompletedTask;
// The original authorize URL for the post-consent redirect.
var originalUrl = OriginalAuthorizeUrl(e);
var scopesArr = string.IsNullOrEmpty(scopes)
? Array.Empty()
: scopes!.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var msg = e.HasOut ? e.Out! : e.In;
// Header-driven content negotiation: a BFF that wants to render its own native
// consent UI sends X-Identity-Delegate-Consent: 1. We answer with a machine-
// readable 400 JSON body instead of the browser 302 to /consent — the BFF then
// hosts its own /consent Razor page and POSTs to /me/consents to grant.
var delegateHeader = e.In.GetHeader("X-Identity-Delegate-Consent");
if (string.Equals(delegateHeader, "1", StringComparison.Ordinal)
|| string.Equals(delegateHeader, "true", StringComparison.OrdinalIgnoreCase))
{
msg.Body = new Dictionary
{
["error"] = "consent_required",
["clientId"] = clientId,
["appName"] = appName ?? clientId,
["scopes"] = scopesArr,
["userId"] = userId ?? "",
["returnUrl"] = originalUrl
};
msg.Headers[HttpHeaders.ResponseCode] = 400;
msg.Headers["Content-Type"] = "application/json; charset=utf-8";
return Task.CompletedTask;
}
var consentUserId = userId is not null && long.TryParse(userId, out var parsedUid) ? parsedUid : 0;
var consentTicket = ticketService.ProtectConsent(new ConsentTicket(
UserId: consentUserId,
ClientId: clientId,
AppName: appName ?? clientId,
Scopes: scopes ?? "",
ReturnUrl: originalUrl));
var redirectUrl = $"{consentPath}?ct={Uri.EscapeDataString(consentTicket)}";
msg.Body = Array.Empty();
msg.Headers[HttpHeaders.ResponseCode] = 302;
msg.Headers["Location"] = redirectUrl;
return Task.CompletedTask;
}
private static string? ParseCookieValue(string cookieHeader, string name)
{
foreach (var part in cookieHeader.Split(';', StringSplitOptions.TrimEntries))
{
var eqIdx = part.IndexOf('=');
if (eqIdx <= 0) continue;
if (part[..eqIdx].Trim().Equals(name, StringComparison.Ordinal))
return part[(eqIdx + 1)..].Trim();
}
return null;
}
}
Path: redb-identity/src/redb.Identity.Http/Security/SessionTicketService.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/Security/SessionTicketService.cs
----
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using redb.Identity.Contracts.Common;
namespace redb.Identity.Http.Security;
///
/// Encrypts/decrypts session tickets using ASP.NET DataProtection.
/// A session ticket is a compact encrypted blob containing the user ID, session ID, and username.
/// Cookie-based: self-contained, no DB lookup on every request (except revocation check).
///
public sealed class SessionTicketService
{
private const string Purpose = "redb.identity.session";
private const string ReauthPurpose = "redb.identity.reauth";
private const string ConsentPurpose = "redb.identity.consent";
private const byte Version1 = 1;
private const byte Version2 = 2;
private readonly IDataProtector _protector;
private readonly IDataProtector _reauthProtector;
private readonly IDataProtector _consentProtector;
private readonly TimeProvider _timeProvider;
private readonly ILogger? _logger;
public SessionTicketService(IDataProtectionProvider provider)
: this(provider, TimeProvider.System, null)
{
}
public SessionTicketService(IDataProtectionProvider provider, TimeProvider? timeProvider)
: this(provider, timeProvider, null)
{
}
public SessionTicketService(
IDataProtectionProvider provider,
TimeProvider? timeProvider,
ILogger? logger)
{
ArgumentNullException.ThrowIfNull(provider);
_protector = provider.CreateProtector(Purpose);
_reauthProtector = provider.CreateProtector(ReauthPurpose);
_consentProtector = provider.CreateProtector(ConsentPurpose);
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = logger;
}
///
/// Signs a re-authentication marker capturing WHICH session was active when the OP forced
/// re-authentication (prompt=login / max_age), together with the instant it did so (for
/// expiry only). DataProtection-encrypted so a client cannot forge it. On the return trip
/// re-auth is satisfied once the ACTIVE session id differs from this one — i.e. the End-User
/// signed in again (a fresh /login always mints a new session). Keying on the session id
/// rather than the second-precision auth_time avoids a same-second window where an
/// unchanged session could otherwise be treated as re-authenticated.
/// is 0 when re-auth was forced with no active session (logged-out prompt=login). A
/// distinct protector purpose keeps it non-interchangeable with session tickets.
///
public string ProtectReauth(long markedSessionId)
{
var payload = new byte[16];
BitConverter.TryWriteBytes(payload.AsSpan(0, 8), markedSessionId);
BitConverter.TryWriteBytes(payload.AsSpan(8, 8), _timeProvider.GetUtcNow().UtcTicks);
return Convert.ToBase64String(_reauthProtector.Protect(payload));
}
///
/// Verifies and decodes a re-authentication marker produced by .
/// Returns the marked session id (and the instant it was requested), or null when the
/// marker is missing, tampered, or older than .
///
public ReauthMarker? UnprotectReauth(string marker, TimeSpan maxAge)
{
if (string.IsNullOrEmpty(marker))
return null;
try
{
var payload = _reauthProtector.Unprotect(Base64Canonical.Decode(marker));
if (payload.Length < 16)
return null;
var markedSessionId = BitConverter.ToInt64(payload, 0);
var requestedAt = new DateTimeOffset(BitConverter.ToInt64(payload, 8), TimeSpan.Zero);
if (_timeProvider.GetUtcNow() - requestedAt > maxAge)
return null;
return new ReauthMarker(markedSessionId, requestedAt);
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "SessionTicketService: failed to decrypt reauth marker.");
return null;
}
}
///
/// Mints a signed consent ticket. The authorization server issues it (after it has
/// decided consent is required) so that the consent page can render — and be granted —
/// only from server-supplied, tamper-proof parameters. Before this, the page rendered
/// app_name /scopes straight from the query string, so a crafted
/// /consent?app_name=Your%20Bank&client_id=attacker link showed the
/// operator's own trusted UI attributing an attacker's client to a familiar name. The
/// ticket also carries the user it was minted for, so the grant POST can refuse a ticket
/// replayed under a different session. A distinct protector purpose keeps it
/// non-interchangeable with session tickets.
///
public string ProtectConsent(ConsentTicket ticket)
{
ArgumentNullException.ThrowIfNull(ticket);
var withStamp = ticket with { IssuedAt = _timeProvider.GetUtcNow() };
var payload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(withStamp);
return Convert.ToBase64String(_consentProtector.Protect(payload));
}
///
/// Verifies and decodes a consent ticket produced by .
/// Returns null when the ticket is missing, tampered, or older than
/// .
///
public ConsentTicket? UnprotectConsent(string ticket, TimeSpan maxAge)
{
if (string.IsNullOrEmpty(ticket))
return null;
try
{
var payload = _consentProtector.Unprotect(Base64Canonical.Decode(ticket));
var decoded = System.Text.Json.JsonSerializer.Deserialize(payload);
if (decoded is null)
return null;
if (_timeProvider.GetUtcNow() - decoded.IssuedAt > maxAge)
return null;
return decoded;
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "SessionTicketService: failed to decrypt consent ticket.");
return null;
}
}
///
/// Creates an encrypted session ticket for the given user and session.
/// Format v2: [version:1][userId:8][sessionId:8][issuedUtcTicks:8][usernameUtf8:rest]
///
public string Protect(long userId, long sessionId, string username)
{
ArgumentNullException.ThrowIfNull(username);
var usernameBytes = System.Text.Encoding.UTF8.GetBytes(username);
var payload = new byte[1 + 8 + 8 + 8 + usernameBytes.Length];
payload[0] = Version2;
BitConverter.TryWriteBytes(payload.AsSpan(1, 8), userId);
BitConverter.TryWriteBytes(payload.AsSpan(9, 8), sessionId);
BitConverter.TryWriteBytes(payload.AsSpan(17, 8), _timeProvider.GetUtcNow().UtcTicks);
usernameBytes.CopyTo(payload.AsSpan(25));
var encrypted = _protector.Protect(payload);
return Convert.ToBase64String(encrypted);
}
///
/// Decrypts a session ticket. Returns null if the ticket is invalid, tampered, or expired.
/// Supports both v1 (no sessionId) and v2 (with sessionId) formats for rolling upgrade.
///
public SessionTicket? Unprotect(string ticket, TimeSpan maxAge)
{
if (string.IsNullOrEmpty(ticket))
return null;
try
{
var encrypted = Base64Canonical.Decode(ticket);
var payload = _protector.Unprotect(encrypted);
if (payload.Length < 17)
return null;
var version = payload[0];
if (version == Version2 && payload.Length >= 25)
{
var userId = BitConverter.ToInt64(payload, 1);
var sessionId = BitConverter.ToInt64(payload, 9);
var issuedTicks = BitConverter.ToInt64(payload, 17);
var issuedAt = new DateTimeOffset(issuedTicks, TimeSpan.Zero);
if (_timeProvider.GetUtcNow() - issuedAt > maxAge)
return null;
var username = System.Text.Encoding.UTF8.GetString(payload, 25, payload.Length - 25);
return new SessionTicket(userId, username, issuedAt, sessionId);
}
if (version == Version1)
{
var userId = BitConverter.ToInt64(payload, 1);
var issuedTicks = BitConverter.ToInt64(payload, 9);
var issuedAt = new DateTimeOffset(issuedTicks, TimeSpan.Zero);
if (_timeProvider.GetUtcNow() - issuedAt > maxAge)
return null;
var username = System.Text.Encoding.UTF8.GetString(payload, 17, payload.Length - 17);
return new SessionTicket(userId, username, issuedAt, SessionId: 0);
}
return null;
}
catch (Exception ex)
{
// Tampered ciphertext OR DataProtection key rotation. Return null to keep the
// public contract intact (treated as "no valid session"), but make sure operators
// see decrypt failures \u2014 a sustained run is a security signal.
_logger?.LogWarning(ex,
"SessionTicketService: failed to decrypt session ticket (length={Length}).",
ticket.Length);
return null;
}
}
}
///
/// Decrypted session ticket data.
///
public sealed record SessionTicket(long UserId, string Username, DateTimeOffset IssuedAt, long SessionId = 0);
///
/// Server-signed consent parameters. Every field is set by the authorization server, never
/// by the browser: and are what the page displays,
/// and are what the grant records, and
/// is the user it was minted for (the grant POST requires the session to
/// match). is stamped by .
///
public sealed record ConsentTicket(
long UserId, string ClientId, string AppName, string Scopes, string ReturnUrl, DateTimeOffset IssuedAt = default);
///
/// Decrypted re-authentication marker: the session that was active when re-auth was forced
/// (0 = none / logged out) and the instant it was requested (expiry only).
///
public readonly record struct ReauthMarker(long MarkedSessionId, DateTimeOffset RequestedAt);
Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.example.json
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.example.json
----
{
"//": [
"redb.Identity.Http module configuration template (Tsak Layer 4: {Module}.config.json).",
"This file ships inside the .tpkg and provides the HTTP transport defaults for the",
"Identity HTTP facade. Phase 8: the facade runs in its OWN RouteContext",
"('identity.http') and exchanges with redb.Identity.Core ('identity') exclusively",
"through `direct-vm://identity-*` brokered messages whose DTOs live in",
"redb.Identity.Contracts. The two modules no longer share a context or DI.",
"",
"Override any value via the standard Tsak 5-layer pipeline:",
" Layer 1 (host appsettings): Tsak:Contexts:default:IdentityTransport:*",
" Layer 2 (per-context): Tsak:Contexts:{contextName}:IdentityTransport:*",
" Layer 3 (context.json): same shape as below, merged before this file",
" Layer 4 (THIS file): defaults shipped with the .tpkg",
" Layer 5 (Override, wins): Tsak:Contexts:{contextName}:Override:IdentityTransport:*",
"",
"Environment-variable overrides use the standard .NET IConfiguration mapping, e.g.:",
" Tsak__Contexts__identity__Override__IdentityTransport__Http__PublicPort=8443",
" Tsak__Contexts__identity__Override__IdentityTransport__Http__CorsEnabled=true",
"",
"PRODUCTION CHECKLIST (per docs/IDENTITY_DEPLOYMENT.md):",
" \u2022 Bind PublicPort behind a TLS-terminating reverse proxy (nginx/HAProxy/ALB).",
" \u2022 Set ManagementPort to a separate value (e.g. 8081) and firewall it off from",
" the public internet \u2014 the management API is admin-only and never exposes CORS.",
" \u2022 Keep CorsRegisteredClientOriginsEnabled=true so onboarding new SPAs via the",
" management API automatically grants them CORS access \u2014 no config redeploys.",
" \u2022 Use AdditionalAllowedOrigins ONLY for dev/staging fallbacks that have no",
" OAuth client of their own. NEVER set it to '*'."
],
"ContextName": "identity.http",
"AutoStart": true,
"//RedbInstanceName": [
"Phase 9b: identifies the named IRedbService the HTTP facade uses to back the",
"shared cluster-wide DataProtection key-ring. MUST point at the SAME database as",
"redb.Identity.Core's RedbInstanceName so cookies issued by either context decrypt",
"with either. The HTTP facade has no project-reference on Core \u2014 the only thing it",
"shares with Core is the DP key-ring (rows in the PROPS store) plus the application",
"name 'redb.identity' set in IdentityHttpModuleHost.",
"Override path: Tsak__Contexts__identity.http__Override__RedbInstanceName=."
],
"RedbInstanceName": "identity-pg",
"//Redb": [
"Named IRedbService instances. Tsak's RegisterNamedRedbServices reads this section",
"after context.json/{Module}.config.json merge and registers each entry under",
"'redb-factory:{name}' in the route-context registry. The HTTP facade's child",
"container resolves the factory whose name matches RedbInstanceName above.",
"",
"PRODUCTION: keep ConnectionString out of source control \u2014 supply via Layer-5:",
" Tsak__Contexts__identity.http__Override__Redb__identity-pg__ConnectionString=",
"",
"DEPLOYMENT TIP: place a shared 'context.json' (Layer 3) in the same Libs/ folder as",
"redb.Identity.Core.tpkg + redb.Identity.Http.tpkg containing only the Redb section;",
"both .tpkg will pick it up via Tsak's per-folder context.json merge, eliminating",
"the duplicated block here."
],
"Redb": {
"identity-pg": {
"Provider": "postgres",
"UsePro": true,
"ConnectionString": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true",
"EnsureCreated": true
}
},
"IdentityTransport": {
"Http": {
"//": [
"PublicPort \u2014 OIDC protocol + discovery endpoints (token, userinfo, .well-known/*).",
"ManagementPort \u2014 admin API (/api/v1/identity/*, /scim/*). Null = share PublicPort.",
" Production strongly recommends a separate, firewalled port.",
"CorsEnabled \u2014 master switch. Required for SPA / native PKCE clients calling",
" token / userinfo / revocation from a browser context.",
" Discovery (/.well-known/*) always uses '*' when CorsEnabled=true;",
" browser-redirect endpoints (authorize, login, logout-form) and",
" the management API NEVER receive CORS headers regardless.",
"CorsRegisteredClientOriginsEnabled \u2014 when true (default), the resolver allows any",
" browser Origin matching a registered OAuth application's redirect",
" or post-logout URI. New SPAs onboarded via the management API",
" gain CORS access without any config change.",
"AdditionalAllowedOrigins \u2014 CSV of origins always allowed (dev/staging fallbacks).",
" Per-request matched and echoed as a single origin (browsers reject",
" CSV in Access-Control-Allow-Origin).",
"EnableDeviceCodeFlow \u2014 mounts /connect/deviceauthorization and /connect/device/verify.",
" Must also be enabled in Identity:EnableDeviceCodeFlow.",
"FederationCallbackPath \u2014 path used for IdP redirect-back when EnableFederation=true."
],
"PublicPort": 8080,
"//ManagementPort": "Production: separate port for admin API, e.g. 8081 (firewalled).",
"ManagementPort": null,
"CorsEnabled": false,
"CorsRegisteredClientOriginsEnabled": true,
"//AdditionalAllowedOrigins": "CSV of origins (no trailing slash). Example: 'https://app.dev.local,https://staging.example.com'. NEVER use '*'.",
"AdditionalAllowedOrigins": null,
"EnableDeviceCodeFlow": true,
"FederationCallbackPath": "/connect/federation/callback"
},
"Features": {
"EnablePushedAuthorization": true
}
}
}
Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.json
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/redb.Identity.Http.config.json
----
{
"//": [
"Tsak Layer 4 stub — module identity only.",
"All business config lives in the EXTERNAL Libs/context.json (Layer 3),",
"alongside the .tpkg files. See: redb.Identity.Http.config.example.json for",
"the full annotated template (reference, NOT shipped)."
],
"ContextName": "identity.http",
"AutoStart": true
}
Path: redb-identity/src/redb.Identity.Http/redb.Identity.Http.csproj
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Http/redb.Identity.Http.csproj
----
redb.Identity.Http
redb.Identity.Http
HTTP / HTTPS facade for redb.Identity — OIDC discovery, token, authorize, userinfo, introspect, revoke, JWKS, PAR, DCR, SCIM, /me and management endpoints.
PreserveNewest