using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; namespace ZB.MOM.WW.Auth.AspNetCore; /// /// Applies the hardened cookie-authentication defaults shared by ZB.MOM.WW apps: /// HTTP-only, , sliding expiration, a caller-supplied idle /// timeout, and a configurable HTTPS requirement. /// /// /// The cookie name is intentionally left untouched: each app owns its own cookie name /// (so two apps on the same host do not clobber each other's session), and the caller sets it /// when configuring the cookie scheme. /// public static class ZbCookieDefaults { /// /// Default idle timeout used when a caller does not supply one. After this much inactivity /// the (sliding) session cookie expires and the principal must re-authenticate. /// public static readonly TimeSpan DefaultIdleTimeout = TimeSpan.FromMinutes(30); /// /// Applies the hardened defaults to . /// /// The cookie-authentication options to mutate. /// /// When (the default), the cookie is only ever sent over HTTPS /// (). Set to only for local /// development over plain HTTP (: Secure is /// still set when the current request is HTTPS, which is safer than None). /// /// /// The sliding idle timeout. Defaults to when not specified. /// /// is . public static void Apply( CookieAuthenticationOptions options, bool requireHttps = true, TimeSpan? idleTimeout = null) { ArgumentNullException.ThrowIfNull(options); options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Strict; options.Cookie.SecurePolicy = requireHttps ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest; options.SlidingExpiration = true; options.ExpireTimeSpan = idleTimeout ?? DefaultIdleTimeout; } }