ApiFeatures.Authentications.Sessions 9.2.0

dotnet add package ApiFeatures.Authentications.Sessions --version 9.2.0
                    
NuGet\Install-Package ApiFeatures.Authentications.Sessions -Version 9.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ApiFeatures.Authentications.Sessions" Version="9.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ApiFeatures.Authentications.Sessions" Version="9.2.0" />
                    
Directory.Packages.props
<PackageReference Include="ApiFeatures.Authentications.Sessions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ApiFeatures.Authentications.Sessions --version 9.2.0
                    
#r "nuget: ApiFeatures.Authentications.Sessions, 9.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ApiFeatures.Authentications.Sessions@9.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ApiFeatures.Authentications.Sessions&version=9.2.0
                    
Install as a Cake Addin
#tool nuget:?package=ApiFeatures.Authentications.Sessions&version=9.2.0
                    
Install as a Cake Tool

ApiFeatures.Authentications.Sessions

Session-based authentication for ASP.NET Core. A client logs in with a username and password and receives an opaque session key. The key travels either in an HTTP-only cookie (the browser keeps it out of JavaScript's reach) or in a header or query-string parameter that the client sends back. Sessions are stored in MongoDB or PostgreSQL and cached in memory or in Redis.

One setting, SessionLocation, decides both directions: how create-session delivers the session and where later requests are read from. The two sides cannot disagree.

Supported frameworks: net9.0 and net10.0.

9.2.0 contains breaking changes. ResponseLocation and its types are removed, and SessionLocation is now the only setting. ISessionFeatureBusinessLogic.IsAuthenticationValidAsync now takes an AuthenticationRequestContext instead of (username, password). ISessionService gains GetUnexpiredByUsernameAsync, and SessionInfoDto is removed (use SessionSummaryDto). CreateSessionPayloadDtoValidator takes SessionMetadataLimitOptions. The MongoDB package now owns the BSON class maps of the session types and no longer registers a global Guid serializer. See Migrating from 9.1 to 9.2.

Contents

Installation

dotnet add package ApiFeatures.Authentications.Sessions
# plus exactly one storage package:
dotnet add package ApiFeatures.Authentications.Sessions.MongoDatabases
dotnet add package ApiFeatures.Authentications.Sessions.Postgresqls

The package builds for net9.0 and net10.0. The .NET 10 SDK is only needed to build this repository, not to consume the package. The package no longer depends on Microsoft.AspNetCore.OpenApi; reference it yourself if your host calls AddOpenApi() / MapOpenApi().

Registration

You provide three things: a clock, your credential check, and a database.

using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.Services.Interfaces;
using BusinessFeatures.Cores.Contexts;

// 1. The clock (the module never reads the system time directly)
public class SystemDateTimeContext : IDateTimeContext
{
    public Task<DateTime> GetNowAsync(CancellationToken cancellationToken = default) => Task.FromResult(DateTime.Now);

    public Task<DateTime> GetUtcNowAsync(CancellationToken cancellationToken = default) => Task.FromResult(DateTime.UtcNow);
}

public class SystemDateTimeOffsetContext : IDateTimeOffsetContext
{
    public Task<DateTimeOffset> GetNowAsync(CancellationToken cancellationToken = default) => Task.FromResult(DateTimeOffset.Now);

    public Task<DateTimeOffset> GetUtcNowAsync(CancellationToken cancellationToken = default) => Task.FromResult(DateTimeOffset.UtcNow);
}

// 2. Your credential check
public class MySessionBusinessLogic : ISessionFeatureBusinessLogic
{
    private static readonly string[] KnownTenants = ["acme", "globex"];

    public Task<bool> IsAuthenticationValidAsync(AuthenticationRequestContext requestContext, CancellationToken cancellationToken = default)
    {
        // Your own rule on the client metadata (here: a known tenant is required)
        if (!requestContext.Metadata.TryGetValue("tenant", out var tenant) || !KnownTenants.Contains(tenant))
        {
            return Task.FromResult(false);
        }

        // Verify the credentials against your user store. Return false for invalid credentials (the module answers 401).
        return Task.FromResult(requestContext.Username == "demo" && requestContext.Password == "demo-password");
    }

    public Task OnUserAuthenticatedAsync(HttpContext httpContext, CancellationToken cancellationToken = default)
    {
        // Runs after the middleware authenticated a request (optional hook)
        return Task.CompletedTask;
    }
}
using ApiFeatures.Authentications.Sessions.Extensions;
using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.MongoDatabases.Extensions;
using ApiFeatures.Authentications.Sessions.MongoDatabases.Models.Options;

var builder = WebApplication.CreateBuilder(args);

var feature = new AddSessionAuthenticationFeatureOptions
{
    Scheme = "Session",
    SessionLocation = new CookieSessionLocation("SessionToken")
}
.WithDateTimeContext<SystemDateTimeContext>()
.WithDateTimeOffsetContext<SystemDateTimeOffsetContext>()
.WithBusinessLogic<MySessionBusinessLogic>()
.WithMongoDatabase(new MongoSessionAuthenticationDatabaseOptions
{
    ConnectionString = "mongodb://localhost:27017",
    DatabaseName = "SessionAuthenticationDb",
    Collection = new MongoDatabaseCollectionOptions { Sessions = "sessions" }
});

builder.Services.AddSessionAuthenticationFeature(feature);
  • Never assign AddSessionAuthenticationFeatureOptions.Database. AddSessionAuthenticationFeature throws InvalidOperationException for a non-null Database. The database goes in through WithMongoDatabase(...) (package ...Sessions.MongoDatabases) or WithPostgresDatabase(...) (package ...Sessions.Postgresqls).
  • PostgreSQL also needs an ISessionEntityOptions in DI that names the columns, for example services.AddSingleton<ISessionEntityOptions, MyEntityOptions>().
  • The module throws business exceptions (a validation failure becomes 400, wrong credentials 401). The host must translate them, for example with UseGenericExceptionHandler() from ApiFeatures.Commons or your own exception middleware. Without one they surface as 500.
  • Scheme is the prefix of the Authorization: <Scheme> <key> header (for example Session). It is also the authentication type of the middleware's principal.
  • Storage selects the session cache, see Session storage.

Reading the settings from appsettings.json is up to the host. The sample app (see Sample app) shows one way, including a converter for the Location section.

Credential check and client metadata

IsAuthenticationValidAsync receives an AuthenticationRequestContext with everything the client sent to create-session, so you can add your own rules (for example "this tenant is not allowed to sign in") before a session is created.

Member Meaning
Username, Password The credentials from the request
Device A copy of the device information (Name, Model)
Browser A copy of the browser information, or null when none was sent
Metadata The client metadata: a read-only map that is never null (empty when none was sent)
HttpContext The current request, for example to read a header
using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.Services.Interfaces;

public class TenantAwareBusinessLogic : ISessionFeatureBusinessLogic
{
    public Task<bool> IsAuthenticationValidAsync(AuthenticationRequestContext requestContext, CancellationToken cancellationToken = default)
    {
        // Metadata is never null; a missing key simply is not found
        var appVersion = requestContext.Metadata.GetValueOrDefault("appVersion");
        if (appVersion == "0.9")
        {
            return Task.FromResult(false);   // block an outdated client: the module answers 401
        }

        return Task.FromResult(requestContext.Username == "demo" && requestContext.Password == "demo-password");
    }

    public Task OnUserAuthenticatedAsync(HttpContext httpContext, CancellationToken cancellationToken = default) => Task.CompletedTask;
}
  • false means 401 INVALID_CREDENTIALS, and no session is created. This holds for every session location.
  • An exception thrown by your code is not turned into 401. It goes to the host's exception handling (500 with a typical host), and no session or cookie is created.
  • The hook runs after the payload validation. A request that fails validation (including the metadata limits) never reaches it.
  • Keys that differ only by case (Tenant and tenant) are two entries, and empty-string values are kept as sent.
  • OnUserAuthenticatedAsync is unchanged. It runs after the middleware authenticated a request, on every authenticated request.
  • The module never logs the password. AuthenticationRequestContext.ToString() does not print it either.
  • You can build an AuthenticationRequestContext yourself in unit tests: the constructor is public and throws ArgumentNullException for every argument except browser.

Metadata limits

The create-session payload accepts an optional metadata object (string keys and string values). It is size-limited so that a client cannot push large blobs into your credential check or your session store.

Limit Property Default
Number of entries MaxEntryCount 20
Key length MaxKeyLength 64
Value length MaxValueLength 1024

Lengths are measured in characters: string.Length, which counts UTF-16 code units, so most emoji count as 2. A limit is inclusive: exactly at the limit is accepted, one over is rejected.

using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.Models.Options;

var feature = new AddSessionAuthenticationFeatureOptions
{
    // Replaces the defaults; every value must be greater than 0. Null keeps the defaults.
    MetadataLimits = new SessionMetadataLimitOptions { MaxEntryCount = 10, MaxKeyLength = 32, MaxValueLength = 512 }
};

A payload that breaks a limit gets 400 and your hook is not called. The messages do not contain the key or value; whether the 400 body echoes the attempted value depends on the host's error handler (the Commons GenericExceptionMiddleware does):

Problem Message
More entries than MaxEntryCount Metadata must not contain more than {MaxEntryCount} entries.
Empty or whitespace key Metadata keys must not be empty or whitespace.
Key longer than MaxKeyLength Metadata keys must not exceed {MaxKeyLength} characters.
Null value Metadata values must not be null.
Value longer than MaxValueLength Metadata values must not exceed {MaxValueLength} characters.

Missing, null and {} metadata are all valid and are not subject to the limits. Business rules about the content (allowed keys, allowed values) are yours, in the credential check.

Stored metadata

Metadata that passes the limits and your credential check is stored with the session (MongoDB, PostgreSQL and the session cache) and is returned to the signed-in user by GET /api/sessions.

  • Do not put passwords, tokens, one-time codes, captcha responses or any other secret in metadata. It is visible to the user and is kept as long as the session exists.
  • Send one-time tokens in a request header instead and read them through requestContext.HttpContext in your credential check, so they are never stored.
  • Good candidates are non-sensitive labels such as tenant, appVersion or locale.
  • The metadata of a session cannot be changed after login. Sessions created by an earlier build load with no metadata.

Choosing a SessionLocation

SessionLocation is a property of AddSessionAuthenticationFeatureOptions. It is nullable and has no default.

SessionLocation create-session returns Requests are read from
new CookieSessionLocation("SessionToken") 200 {} and a Set-Cookie. The key is never in the body. The cookie SessionToken, then Authorization: <Scheme> <key>
new HttpHeaderSessionLocation("X-Session-Key") 200 with the session in the body (SessionResultDto) The header X-Session-Key, then Authorization: <Scheme> <key>
new QueryStringSessionLocation("session_key") 200 with the session in the body The query parameter session_key, then Authorization: <Scheme> <key>
null (default) 200 with the session in the body Authorization: <Scheme> <key> only

Body response (header, query string and null):

{ "accessToken": "<key>", "type": "Session", "expiryTime": null }

Cookie response: the body is exactly {} and the key is only in the cookie.

  • The Authorization fallback belongs to the middleware. UseSessionAuthentication() tries the configured location first and then the Authorization header. The authentication handler does not fall back: it reads only its effective location (see Authentication paths).
  • A header location named Authorization is parsed as <Scheme> <key>. With a module Scheme set, a different prefix is ignored. The handler applies the same rule: a handler scheme now enforces the module Scheme prefix on Authorization.
  • Query-string keys can end up in access logs, proxies and browser history. Prefer a cookie or a header.
  • A stale or expired key on an endpoint marked [AllowAnonymous] does not block the request. On any other endpoint the middleware answers 401.

CookieSessionLocation properties:

Property Type Default Meaning
Name string required Cookie name (constructor argument)
HttpOnly bool true Keeps the cookie out of JavaScript
Secure bool true Sent over HTTPS only. Required when SameSite is None or Partitioned is true
SameSite SameSiteMode Lax Strict, Lax, None (cross-site requests) or Unspecified
Domain string? null Host-only cookie when null. Passed through as configured
Path string "/" Must start with /
Partitioned bool false CHIPS partitioned cookie. Requires Secure = true
ExpiryTime CookieTime? null Lifetime of the session, see below
using ApiFeatures.Authentications.Sessions.Constants;
using ApiFeatures.Authentications.Sessions.Models;
using Microsoft.AspNetCore.Http;

var location = new CookieSessionLocation("SessionToken")
{
    HttpOnly = true,
    Secure = true,
    SameSite = SameSiteMode.None,
    Domain = ".example.com",
    Path = "/",
    Partitioned = false,
    ExpiryTime = new CookieTime { Value = 7, Unit = CookieTimeUnits.Day }
};
  • ExpiryTime is a CookieTime { Value, Unit } with Unit one of Second, Minute, Hour, Day. Null means a browser-session cookie (no Expires or Max-Age) and a stored session with no expiry. When set, the cookie's Expires and the stored session's expiry are the same instant: the creation time in UTC, taken from your IDateTimeContext, plus the value.
  • Domain: a host may set a cookie only for its own registrable domain or a parent of it. The module passes the value through and cannot check it against the API host. A wrong domain makes the browser drop the cookie silently.
  • Browsers cap cookie lifetime. Chrome caps it at 400 days, so an ExpiryTime longer than that outlives the cookie: the browser drops the cookie while the server-side session is still valid.
  • Create-time overflow (an expiry past the year 9999) fails with 500 and the code SESSION_EXPIRY_OUT_OF_RANGE; no cookie is set and no session is stored.

Startup validation

AddSessionAuthenticationFeature validates the cookie location and throws InvalidOperationException (Invalid session cookie configuration: ...) so that a setup that browsers would reject silently fails at startup instead:

Rule Message (abridged)
SameSite = None needs Secure = true SessionLocation.SameSite is None but SessionLocation.Secure is false
Partitioned = true needs Secure = true SessionLocation.Partitioned is true but SessionLocation.Secure is false
Name must not be empty SessionLocation.Name must not be empty for a cookie location
ExpiryTime.Value > 0 SessionLocation.ExpiryTime.Value must be greater than 0
ExpiryTime.Unit is a defined unit SessionLocation.ExpiryTime.Unit must be Second, Minute, Hour or Day
ExpiryTime fits in a TimeSpan SessionLocation.ExpiryTime is too large to represent as a duration
Path starts with / SessionLocation.Path must start with '/'
__Secure- name prefix needs Secure = true ... uses the __Secure- prefix, which requires SessionLocation.Secure = true
__Host- name prefix needs Secure, no Domain, Path = "/" ... uses the __Host- prefix ...

The metadata limits are validated too: a limit that is zero or negative throws InvalidOperationException (Invalid session metadata limits: MetadataLimits.MaxEntryCount must be greater than 0., and the same for MaxKeyLength and MaxValueLength).

SameSite = Lax or Strict with Secure = false is allowed, for local development over plain HTTP. The origin check has its own startup rules and messages (no Invalid session cookie configuration: prefix); the registration-time ones are thrown by AddSessionAuthenticationFeature, the CORS-policy ones when the app starts. See CSRF origin check.

Logout

DELETE /api/authentication/session

Cookie location: always 204, and always idempotent.

  • The session key is the value of the session cookie. Only when there is no cookie does it come from the authenticated principal's SessionKey claim (for example an Authorization request in the middleware path).
  • The cookie's session is targeted first. A stale cookie together with a valid Authorization header clears the cookie, while the session named by the Authorization header stays live.
  • Only that one session is deleted, never the user's other sessions.
  • The response carries a clearing Set-Cookie with the same attributes as the login cookie (name, Domain, Path, SameSite, Secure, HttpOnly, Partitioned), an epoch Expires and Max-Age=0.
  • It works for expired, revoked, unknown and missing sessions, and a second call also returns 204. The endpoint is anonymous.
  • The session is deleted from the storage first (requests authenticate from there) and then from the database. If either throws, the cookie is kept and the error is returned unchanged (500 with a typical host), so a retry is safe.

Header, query-string and null locations: unchanged. The endpoint requires an authenticated session: 204 with one, 401 without.

Authentication paths: middleware or handler

Pick one path per host.

a) Middleware

using ApiFeatures.Authentications.Sessions.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;

public class ChallengeOnlyHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public ChallengeOnlyHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
        : base(options, logger, encoder)
    {
    }

    // The session middleware authenticates the request itself
    protected override Task<AuthenticateResult> HandleAuthenticateAsync() => Task.FromResult(AuthenticateResult.NoResult());

    protected override Task HandleChallengeAsync(AuthenticationProperties properties)
    {
        Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    }
}

public static class MiddlewarePipeline
{
    public static void Configure(WebApplicationBuilder builder, out WebApplication app)
    {
        builder.Services
            .AddAuthentication("ChallengeOnly")
            .AddScheme<AuthenticationSchemeOptions, ChallengeOnlyHandler>("ChallengeOnly", _ => { });
        builder.Services.AddAuthorization();

        app = builder.Build();

        app.UseCors();
        app.UseSessionAuthentication();
        app.UseAuthentication();
        app.UseAuthorization();
        app.AddSessionAuthenticationEndpoints();
    }
}
  • The middleware sets HttpContext.User with the claims Name, AuthenticationMethod, SessionKey, AuthenticatedAt and, when known, DeviceName, BrowserName and SessionExpiry.
  • Hosts that use only the middleware still need AddAuthorization(), because RequireAuthorization() on protected endpoints (including header/query logout) needs the authorization services, and a scheme that can challenge so an unauthenticated request becomes 401 instead of an exception.

b) Authentication handler

using ApiFeatures.Authentications.Sessions.AuthenticationHandlers;
using ApiFeatures.Authentications.Sessions.Constants;
using ApiFeatures.Authentications.Sessions.Models.Options;
using System.Security.Claims;

public static class HandlerPipeline
{
    public static void Configure(WebApplicationBuilder builder, out WebApplication app)
    {
        builder.Services
            .AddAuthentication("Session")
            .AddScheme<SessionAuthenticationSchemeOptions, SessionAuthenticationHandler>("Session", options =>
            {
                options.BuildAuthenticationPrincipalAsyncHandler = (httpContext, session, cancellationToken) =>
                    Task.FromResult(new ClaimsPrincipal(new ClaimsIdentity(
                    [
                        new Claim(ClaimTypes.Name, session.Username),
                        new Claim(SessionClaimTypes.SessionKey, session.Key)
                    ], "Session")));
            });
        builder.Services.AddAuthorization();

        app = builder.Build();

        app.UseCors();
        app.UseAuthentication();   // no UseSessionAuthentication() in this path
        app.UseAuthorization();
    }
}
  • With no scheme-level location, the handler follows the module's SessionLocation (and falls back to the X-Session-Key header when the module is not registered or has no location). Setting options.SessionLocation on a scheme makes it an extra read-only scheme for that location. Create-session follows only the module setting, never a scheme's.
  • SessionAuthenticationSchemeOptions.SessionLocation is nullable and has no default. Code that assumed the old default and wrote o.SessionLocation.Name = ... now throws NullReferenceException; assign a whole location instead.
  • The handler has no Authorization fallback (only the middleware does).
  • AllowAnonymous = true with a BuildAnonymousPrincipal makes the scheme return an anonymous principal when no key is sent. An empty cookie, header or query value counts as no key.
  • BuildAuthenticationPrincipalAsyncHandler must be set. Add the SessionClaimTypes.SessionKey claim: header/query logout (and cookie logout without a cookie) finds the session through it.
  • Header and query logout use RequireAuthorization(), so the host needs AddAuthorization() and a scheme that can challenge. The handler path above registers one.
  • SessionAuthenticationSchemeOptions.Scheme has an internal setter: do not try to assign it. The scheme prefix is the module's Scheme.

Cross-site setups

Browsers apply SameSite rules to the relationship between the page and the API.

  • Recommended: same-site subdomains. Put the SPA and the API under one registrable domain, for example app.example.com and api.example.com. Use SameSite = Lax (the default), Secure = true and, if you want the cookie visible to both hosts, Domain = ".example.com". This works in every current browser without third-party-cookie exceptions.
  • True cross-site (an SPA at bcd.com calling an API at abc.com): the cookie is a third-party cookie, and whether it is stored and sent depends on each browser's third-party-cookie policy and may change. You need SameSite = None and Secure = true, and optionally Partitioned = true (CHIPS, a cookie keyed to the top-level site). Support for partitioned cookies:
    • Chrome 114 and later, and Firefox 141 and later.
    • Safari: Partitioned shipped in Safari 18.4, was removed in 18.5, and is back in Safari 26.2 and later.
    • Sources (checked 2026-11-11): the WebKit blog post "WebKit Features for Safari 26.2" and the MDN browser-compat-data file Set-Cookie.json.
    • Where partitioned cookies are not available, a true cross-site cookie can be blocked. Use same-site subdomains, or use a header location and keep the key in memory.
  • A 400-day browser cap on cookie lifetime applies, see Cookie options.

CORS

CORS is owned by the host; the module registers no CORS policy. For a credentialed cross-origin cookie you need explicit origins and AllowCredentials(). A wildcard origin cannot be combined with credentials.

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("https://app.example.com")   // explicit origins, never "*"
            .AllowCredentials()                          // required for cookies
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

var app = builder.Build();
app.UseCors();   // before the session middleware or UseAuthentication

The SPA must opt in on every call, including login and logout:

await fetch('https://api.example.com/api/authentication/session', {
  method: 'POST',
  credentials: 'include',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username, password, device: { name: 'browser', model: 'web' } })
});
  • Use exactly ONE of the built-in UseCors or ApiFeatures.Cors.Apis UseDynamicCors per route, never both.
  • Until the ApiFeatures.Cors.Apis problems are fixed, use the built-in CORS for cross-site cookies. ApiFeatures.Cors.Apis currently sends a literal * in Access-Control-Allow-Methods and Access-Control-Expose-Headers on credentialed requests (browsers reject * there when credentials are included) and sends no Vary: Origin. That breaks credentialed preflights, for example the DELETE logout.

CSRF origin check

A cookie that the browser attaches by itself can be abused by another site (CSRF). SameSite=Lax already blocks most of it; the origin check is an opt-in second layer, useful with SameSite=None. It is off by default and registers nothing.

using ApiFeatures.Authentications.Sessions.Models.Options;

var originCheck = new SessionOriginCheckOptions
{
    Enabled = true,
    UseCorsPolicyOrigins = true,   // reuse the origins of the built-in CORS default policy
    AllowedOrigins = ["https://admin.example.com"],   // extra origins, optional
    CorsPolicyName = null          // null = the default policy; only valid with UseCorsPolicyOrigins
};

Assign it to AddSessionAuthenticationFeatureOptions.OriginCheck.

What is checked.

  • State-changing requests (anything except GET, HEAD, OPTIONS, TRACE) that carry the session cookie.
  • Cookie-mode login (the endpoint is checked even without a cookie, because a login CSRF would plant the attacker's session cookie in the victim's browser).
  • Cookie-mode logout without a cookie, unless the request has an Authorization header (browsers never attach that header on their own, so it is not a CSRF vector).

Rules. The Origin header must match an allowed origin exactly (scheme, host, port; default ports and host case are normalised, IDN hosts are compared in their ASCII form). Without an Origin header the Referer origin is used. With neither, the request is rejected. Origin: null, an unparsable value and several Origin values are rejected. A rejected request gets 403 with { "code": "SESSION_ORIGIN_NOT_ALLOWED", "message": "..." }, and a rejected logout keeps the cookie.

Things to know.

  • A same-origin SPA must list its own origin too (browsers send Origin on same-origin POST requests).
  • CLI and other non-browser clients get 403 on cookie-mode login, and on cookie-less logout without Origin, Referer or Authorization. They should use a header location (no cookie, so no check) or send an allowed Origin.
  • The check runs before CORS, so a rejected cross-site request has no CORS headers. In a browser it shows up as a CORS error, not as a readable 403.
  • Do not combine the origin check with form-based UseHttpMethodOverride and ambient Basic authentication that produces a SessionKey claim. A form post could turn into a DELETE after the check ran.
  • Startup rules (InvalidOperationException): enabled with no allowed origin and UseCorsPolicyOrigins = false; an origin that is not scheme://host[:port]; CorsPolicyName without UseCorsPolicyOrigins; a CORS policy that is not registered, allows any origin or has an invalid origin.

Migrating from 9.1 to 9.2

Removed in 9.2.0: SessionResponseLocation, BodySessionResponseLocation, CookieSessionResponseLocation, SessionResponseLocationTypes, and the ResponseLocation property of both AddSessionAuthenticationFeatureOptions and the scheme options. SessionLocation is the single setting for both directions.

9.1 9.2
ResponseLocation = new CookieSessionResponseLocation { CookieName = X, SameSite = s, HttpOnly = h, Secure = c } SessionLocation = new CookieSessionLocation(X) { SameSite = s, HttpOnly = h, Secure = c }
ResponseLocation = new BodySessionResponseLocation() (or unset) with a header or query SessionLocation Keep that SessionLocation (HttpHeaderSessionLocation or QueryStringSessionLocation)
ResponseLocation body or unset, no SessionLocation (clients use Authorization) Leave SessionLocation null
A setup that read a header but wrote a cookie (two different settings) Choose one: a cookie location or a header location
SessionAuthenticationSchemeOptions.SessionLocation had a default Nullable with no default. o.SessionLocation.Name = ... throws NullReferenceException; null follows the module location
Handler scheme ignored the module Scheme prefix on Authorization Enforced: a different prefix is ignored
Cookie logout needed an authenticated session (401 otherwise) Anonymous and idempotent: always 204 and clears the cookie
Cookie had only Name, HttpOnly, Secure, SameSite Adds Domain, Path, Partitioned, ExpiryTime, startup validation, and the opt-in OriginCheck
Microsoft.AspNetCore.OpenApi arrived transitively No longer a dependency; reference it if you use AddOpenApi()
net9.0 only net9.0 and net10.0
IsAuthenticationValidAsync(string username, string password, CancellationToken) IsAuthenticationValidAsync(AuthenticationRequestContext requestContext, CancellationToken). Use requestContext.Username and requestContext.Password; the context also carries Device, Browser, the read-only Metadata and the HttpContext. Breaking: the old signature no longer compiles
Create-session metadata was accepted and silently dropped Validated against the limits (new 400 responses), passed to your hook, and stored with the session and listed by GET /api/sessions
ISessionService had four methods Adds GetUnexpiredByUsernameAsync(string username, DateTime utcNow, CancellationToken). Custom ISessionService implementations must add it (snippet below)
SessionInfoDto (contained the session key and username) Removed. SessionSummaryDto, returned by GET /api/sessions, has no key and no username
new CreateSessionPayloadDtoValidator() new CreateSessionPayloadDtoValidator(SessionMetadataLimitOptions); registered by AddSessionAuthenticationFeature, so only code that creates it directly is affected
MongoDB: you could register your own BSON class maps for SessionEntity or SessionMetadata The ...MongoDatabases package owns those maps. A pre-registered map (or a session serialized before the context was first used) makes the first use of SessionDatabaseContext throw TypeInitializationException with an inner InvalidOperationException that explains the conflict. Remove your registration, and construct the session context before any session is serialized
MongoDB: the package registered a process-wide Guid serializer (Standard representation) It no longer does; the Standard representation is set on the session Id only. If your own code relied on that side effect for other Guid values, the driver 3.x error GuidRepresentation is Unspecified appears: register your own serializer or member map. Stored session data is unchanged
MongoDB: no index guidance Create { Username: 1, CreatedTime: -1 } for the list and a unique { Key: 1 }, see the MongoDatabases README. The library creates no Mongo index

Before:

// 9.1 (does not compile in 9.2)
// ResponseLocation = new CookieSessionResponseLocation { CookieName = "SessionToken", SameSite = SameSiteMode.None, Secure = true }

After:

using ApiFeatures.Authentications.Sessions.Models;
using Microsoft.AspNetCore.Http;

var migrated = new CookieSessionLocation("SessionToken") { SameSite = SameSiteMode.None, Secure = true };

A consumer that ignores metadata changes one line:

using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.Services.Interfaces;

public class MigratedBusinessLogic : ISessionFeatureBusinessLogic
{
    private readonly IUserStore _users;

    public MigratedBusinessLogic(IUserStore users) => _users = users;

    // 9.1 (does not compile in 9.2)
    // public Task<bool> IsAuthenticationValidAsync(string username, string password, CancellationToken cancellationToken = default)
    //     => _users.CheckAsync(username, password, cancellationToken);

    // 9.2: use the context members instead
    public Task<bool> IsAuthenticationValidAsync(AuthenticationRequestContext requestContext, CancellationToken cancellationToken = default)
        => _users.CheckAsync(requestContext.Username, requestContext.Password, cancellationToken);

    public Task OnUserAuthenticatedAsync(HttpContext httpContext, CancellationToken cancellationToken = default) => Task.CompletedTask;
}

public interface IUserStore
{
    Task<bool> CheckAsync(string username, string password, CancellationToken cancellationToken);
}

A custom ISessionService must implement the new list member. The expected rule: the user's sessions whose expiry is null or not earlier than utcNow (a session is expired only when ExpiryTime < utcNow, the same rule as authentication), newest CreatedTime first, an empty list when there are none, ArgumentNullException for a null username, and ArgumentException for an empty username or a utcNow that is not UTC. Read the database, not the cache:

using ApiFeatures.Authentications.Sessions.Models.Entities;

public static class SessionQueries
{
    public static IReadOnlyList<SessionEntity> GetUnexpiredByUsername(IEnumerable<SessionEntity> sessions, string username, DateTime utcNow)
    {
        ArgumentException.ThrowIfNullOrEmpty(username);
        if (utcNow.Kind != DateTimeKind.Utc)
        {
            throw new ArgumentException("utcNow must be a UTC DateTime.", nameof(utcNow));
        }

        return sessions
            .Where(s => s.Username == username && (s.ExpiryTime == null || s.ExpiryTime >= utcNow))
            .OrderByDescending(s => s.CreatedTime)
            .ToList();
    }
}

Endpoints reference

Mapped by app.AddSessionAuthenticationEndpoints().

POST /api/authentication/session (create session)

Anonymous. Request:

{
  "username": "demo",
  "password": "demo-password",
  "device": { "name": "Pixel 9", "model": "Pixel 9" },
  "browser": { "name": "Chrome", "version": "130" },
  "metadata": { "tenant": "acme", "appVersion": "1.4" }
}

metadata is optional, see Metadata limits and Stored metadata.

Status When
200 Cookie location: body {} and a Set-Cookie. Otherwise { accessToken, type, expiryTime }
400 The payload failed validation (device is required, or the metadata limits were exceeded)
401 IsAuthenticationValidAsync returned false
403 Cookie location with the origin check on and a disallowed origin
500 SESSION_EXPIRY_OUT_OF_RANGE

DELETE /api/authentication/session (logout)

Location Status
Cookie 204 always (403 with the origin check on and a disallowed origin)
Header, query string, null 204 with an authenticated session, 401 without

Maximum lengths: key 512, username 256, device name and model 512, browser name and version 512. The metadata limits are configurable.

GET /api/sessions (list my sessions)

Lists the signed-in user's own sessions on every device (matched by username). It is always mapped by app.AddSessionAuthenticationEndpoints(), needs an authenticated session, and works for every session location and both authentication paths. The origin check does not apply to this GET.

Response 200, a plain JSON array (no pagination), newest createdTime first, [] when there are none:

[
  {
    "id": "0193a1c2-6f1e-7b3a-9c0d-5a4e8f21b7d3",
    "device": { "name": "Pixel 9", "model": "Pixel 9" },
    "browser": { "name": "Chrome", "version": "130" },
    "createdTime": "2026-11-12T09:00:00+00:00",
    "expiryTime": "2026-11-19T09:00:00+00:00",
    "isCurrent": true,
    "metadata": { "tenant": "acme" }
  },
  {
    "id": "0193a0ff-1c22-7d10-8e5b-2b9a4c6d0e11",
    "device": { "name": "MacBook", "model": null },
    "browser": null,
    "createdTime": "2026-11-10T08:00:00+00:00",
    "expiryTime": null,
    "isCurrent": false,
    "metadata": {}
  }
]
  • The session key is never returned, not even the caller's own, and the response has no username. id is an opaque identifier. It is not a credential and cannot be turned back into a key.
  • isCurrent is true for the session that made this request. Normally exactly one item is current.
  • Expired sessions are left out but not deleted. A session is expired only when expiryTime < now, the same rule as authentication, so a session expiring exactly now is still listed. A session with no expiry (expiryTime: null) is always listed.
  • metadata is the map the client sent at login ({} when none). It is shown to the user: see Stored metadata.
  • Times are UTC with an explicit offset (+00:00).
  • The list is read from the database. The session cache is only used to find the calling session, and the user comes from that stored session, not from the principal's name.
  • isCurrent edge cases. If the calling session exists in the cache but not in the database (or was deleted while the request ran), the list can be empty or lack a current item, and still answers 200. The same happens when the calling session expires in the milliseconds between authentication and the list query: it is then no longer unexpired, so the list has no current item. A principal without the SessionKey claim, or one whose session is no longer in the cache, gets 401.
Status When
200 The array above
401 No session, an unknown or expired session, a principal without the SessionKey claim, or a session that is no longer in the cache

API documentation

With AddOpenApi() and MapOpenApi() in the host, the create-session response schema is CookieSessionResultDto for a cookie location and SessionResultDto otherwise.

Session storage

Requests authenticate from a fast cache (ISessionStorage), configured with AddSessionAuthenticationFeatureOptions.Storage. The database is the source of truth. GET /api/sessions reads the database through ISessionService; the cache is only used to find the calling session. The client metadata is stored in the database and in the cache.

  • In-memory (default): Storage = null or new InMemorySessionStorageOptions(). Single-instance hosts only.
  • Redis: for several instances.
using ApiFeatures.Authentications.Sessions.Models.Options.SessionStorages;

var storage = new RedisSessionStorageOptions
{
    Host = "localhost",
    Port = 6379,
    InstanceName = "MyApp:"
};
Property Type Default Description
Host string required Redis server address
Port int 6379 Redis server port
Password string? null Password
Username string? null ACL user (Redis 6+)
InstanceName string? null Key prefix, for example MyApp:
Database int 0 Database number
ConnectTimeout int 5000 Milliseconds
SyncTimeout int 5000 Milliseconds
AbortOnConnectFail bool false Abort or retry on connection failure
Ssl bool false TLS (required for Azure Redis)

Security notes

  • Prefer a cookie location with HttpOnly = true and Secure = true: JavaScript cannot read the key, so XSS cannot steal it.
  • Never echo the session key from your own endpoints when you use a cookie location. That would hand the key to JavaScript and defeat HttpOnly.
  • Use HTTPS everywhere. SameSite=None requires it.
  • Treat the key as a password: it grants the session until it expires or is deleted. Keep ExpiryTime short for sensitive apps.
  • Turn the origin check on for SameSite=None cookies.
  • Client metadata is visible to the user through GET /api/sessions. Never put passwords, tokens or other secrets in it, see Stored metadata.
  • The list never contains a session key. The session id it returns is not a secret and cannot be used to authenticate.

Sample app

The repository contains a runnable host, src/apps/ApiFeatures.Applications.Authentication.Sessions. It shows the unified Location bound from configuration (every cookie option), credentialed CORS, the origin check, both authentication paths and probe endpoints.

docker run -d --name sessions-mongo -p 27017:27017 mongo:7
cd src/apps/ApiFeatures.Applications.Authentication.Sessions
dotnet run --launch-profile https      # https://localhost:7245 (a Secure cookie needs HTTPS)
Key Purpose Default
Authentication:Session:Location Type Cookie, HttpHeader, QueryString or None; Name; cookie only: HttpOnly, Secure, SameSite, Domain, Path, Partitioned, ExpiryTime:Value and ExpiryTime:Unit. A blank value counts as not set cookie SessionToken, SameSite=None, 7 days
Authentication:Session:Database Type Mongo or Postgres, passed to WithMongoDatabase / WithPostgresDatabase Mongo on localhost
Authentication:Session:OriginCheck Enabled, UseCorsPolicyOrigins, AllowedOrigins, CorsPolicyName enabled, reuses the CORS origins
Cors:AllowedOrigins SPA origins of the credentialed CORS policy (required) https://localhost:4200
Sample:Handler:Enabled true = authentication handler pipeline, no middleware false
Sample:Handler:AllowAnonymous, SchemeAHeader, SchemeBQuery Handler mode: anonymous principal, extra read-only schemes /api/handler/scheme-a (header) and /api/handler/scheme-b (query) off
Sample:Handler:ExposeSessionKeyInWhoami Test runs only. Makes /api/handler/whoami return the session key. This hands the key to JavaScript and defeats HttpOnly: never enable it outside a QA or test run false
Sample:Credentials:Mode AcceptAll, or Fixed (only Username / Password are valid) AcceptAll
Sample:Credentials:RequiredMetadataKey When set, a login must send this metadata key with a non-blank value, otherwise 401 (for example tenant) unset (rule off)
Authentication:Session:MetadataLimits MaxEntryCount, MaxKeyLength, MaxValueLength (module defaults 20 / 64 / 1024) module defaults
Sample:Overlay Semicolon-separated JSON files loaded last, for example harness/cors-app-example.json;harness/r3-cookie-samesite-none.json none

Two overlays switch the metadata features on for a QA run: harness/metadata-required.json (RequiredMetadataKey = tenant) and harness/metadata-limits-small.json (2 entries, keys 16, values 32). To try the sessions list (the sample uses a cookie location by default, so keep the cookie jar and send the SPA origin):

export Sample__Overlay="harness/metadata-required.json"
# in another shell, log in twice with different devices and metadata
curl -k -c jar1.txt -H "Origin: https://localhost:4200" -H "Content-Type: application/json" \
  -d '{"username":"u","password":"p","device":{"name":"laptop","model":"m"},"metadata":{"tenant":"acme"}}' \
  https://localhost:7245/api/authentication/session
curl -k -c jar2.txt -H "Origin: https://localhost:4200" -H "Content-Type: application/json" \
  -d '{"username":"u","password":"p","device":{"name":"phone","model":"m"},"metadata":{"tenant":"acme"}}' \
  https://localhost:7245/api/authentication/session
# list with the second session: two items, newest first, one isCurrent, no keys
curl -k -b jar2.txt https://localhost:7245/api/sessions

Probe endpoints: GET /api/profile, GET /api/ping (neither returns the session key), GET /api/handler/whoami, /api/handler/protected, POST|PUT|PATCH|DELETE /api/probe/state (counts calls) and GET /api/probe/counter. Configuration sources, lowest to highest precedence: appsettings.json, appsettings.{Environment}.json, user secrets (Development only), environment variables (for example Authentication__Session__Location__SameSite=Lax), command-line arguments, and finally the Sample:Overlay files in the order listed, so an overlay overrides environment variables too.

The https launch profile runs in Production on purpose: in Development, user secrets override appsettings.json and can silently replace the shipped location or database. Use the http (Development) profile only when you want your own user secrets.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on ApiFeatures.Authentications.Sessions:

Package Downloads
ApiFeatures.Authentications.Sessions.Postgresqls

Package Description

ApiFeatures.Authentications.Sessions.MongoDatabases

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
9.2.0 250 11/12/2026
9.1.0 132 10/23/2026
9.0.0 287 5/7/2026

ApiFeatures.Authentications.Sessions 9.2.0 contains BREAKING CHANGES to session location configuration: ResponseLocation and the SessionResponseLocation, BodySessionResponseLocation, CookieSessionResponseLocation and SessionResponseLocationTypes types are removed; SessionLocation is now the single setting for both how create-session returns the session and where requests are read from (see "Migrating from 9.1 to 9.2" in the README). SessionAuthenticationSchemeOptions.SessionLocation is now nullable with no default, so code that assigns o.SessionLocation.Name throws NullReferenceException, and a handler scheme now enforces the module Scheme prefix on the Authorization header. New: cookie Domain, Path, Partitioned and ExpiryTime, startup validation, idempotent cookie logout, and an opt-in Origin (CSRF) check. 9.2.0 adds a .NET 10 (net10.0) build; .NET 9 is still supported. It no longer depends on Microsoft.AspNetCore.OpenApi; reference it directly if your host uses AddOpenApi/MapOpenApi. Also BREAKING in 9.2.0: ISessionFeatureBusinessLogic.IsAuthenticationValidAsync now takes an AuthenticationRequestContext (username, password, device, browser, read-only client metadata, HttpContext) instead of (username, password); ISessionService gains GetUnexpiredByUsernameAsync (custom implementations must add it); SessionInfoDto is removed (use SessionSummaryDto, which never contains a session key); CreateSessionPayloadDtoValidator takes SessionMetadataLimitOptions. The MongoDatabases package now owns the BSON class maps of SessionEntity and SessionMetadata (a class map registered elsewhere makes the first use of SessionDatabaseContext fail with a TypeInitializationException) and no longer registers a process-wide Guid serializer (code that relied on it for its own Guid values gets the driver 3.x "GuidRepresentation is Unspecified" error and must register its own serializer). New: create-session metadata is validated against configurable limits (MetadataLimits, 400 when exceeded) and stored with the session; GET /api/sessions lists the caller's unexpired sessions without keys. Client metadata is visible to the user, so do not put secrets in it. For MongoDB create the recommended indexes { Username: 1, CreatedTime: -1 } and unique { Key: 1 }.