UserSessionService.Platform 1.0.0.4

dotnet add package UserSessionService.Platform --version 1.0.0.4
                    
NuGet\Install-Package UserSessionService.Platform -Version 1.0.0.4
                    
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="UserSessionService.Platform" Version="1.0.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="UserSessionService.Platform" Version="1.0.0.4" />
                    
Directory.Packages.props
<PackageReference Include="UserSessionService.Platform" />
                    
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 UserSessionService.Platform --version 1.0.0.4
                    
#r "nuget: UserSessionService.Platform, 1.0.0.4"
                    
#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 UserSessionService.Platform@1.0.0.4
                    
#: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=UserSessionService.Platform&version=1.0.0.4
                    
Install as a Cake Addin
#tool nuget:?package=UserSessionService.Platform&version=1.0.0.4
                    
Install as a Cake Tool

UserSessionService.Platform

A .NET library for server-side user session management on the I2e Platform. It centralizes session creation, validation, revocation, and lookup behind a single service interface, with support for SQL Server or Redis as the backing store and an optional in-memory cache for frequently accessed sessions.

Table of contents


What problem does this solve?

Platform applications need a consistent way to manage authenticated user sessions across requests and services. Without a shared library, teams often re-implement the same concerns:

Challenge How this library helps
Duplicate session logic One IUserSessionService API for create, validate, revoke, and lookup
Store coupling Switch between SQL (stored procedures) and Redis via configuration
Repeated database/Redis calls Built-in memory cache layer for hot session reads
Multi-environment hosting Resolves environment from application base URL (e.g. tenant subdomains)
Single active session per user Reuses an existing valid session instead of creating duplicates
Operational flexibility Redis supports connection strings and Azure managed identity

Typical use cases include login flows, session cookies, API authentication middleware, and logout/revocation handling in ASP.NET Core or any app using Microsoft.Extensions.DependencyInjection.


Requirements

Before using this package, ensure the following:

Requirement Details
.NET runtime .NET 10.0 (net10.0)
Dependency injection host ASP.NET Core, worker service, or any host that registers IServiceCollection
SQL provider (optional) SQL Server with the platform session stored procedures (defaults listed below)
Redis provider (optional) Azure Cache for Redis or compatible Redis instance; managed identity supported for Azure deployments

SQL stored procedures (default names)

When using SessionStoreProviderType.Sql, these procedures must exist unless you override the names in options:

  • SIPF_spCreateUserSession
  • SIPF_spGetUserSession
  • SIPF_spGetActiveUserSessionId
  • SIPF_spRevokeUserSession

Installation


### 2. Install the package

```powershell
dotnet add package UserSessionService.Platform --version 1.0.0

Or add directly to your project file:

<PackageReference Include="UserSessionService.Platform" Version="1.0.0" />
Package property Value
Package ID UserSessionService.Platform
Version 1.0.0
Target framework net10.0

Getting started

Step 1 — Register services

In Program.cs (or your composition root), call AddUserSessionServices:

using SEyc.Services.Platform.UserSession.DependencyInjection;
using SEyc.Services.Platform.UserSession.Options;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddUserSessionServices(options =>
{
    options.Provider = SessionStoreProviderType.Sql;
    options.SessionExpiryHours = 12;
    options.MemoryCacheDurationSeconds = 600;
    options.Sql.ConnectionString =
        builder.Configuration.GetConnectionString("UserSession")!;
});

var app = builder.Build();
app.Run();

Program.cs

builder.Services.AddUserSessionServices(
    builder.Configuration
        .GetSection(UserSessionOptions.SectionName)
        .Get<UserSessionOptions>()!);

Step 3 — Inject IUserSessionService

The library registers IUserSessionService as a singleton. Inject it wherever session operations are needed.


Usage examples

Create a session on login

CreateSession accepts a user id and application base URL. The service derives the environment from the URL and returns an existing active session when one is already valid.

using SEyc.Services.Platform.UserSession.Abstractions;
using SEyc.Services.Platform.UserSession;

public sealed class AuthService
{
    private readonly IUserSessionService _sessions;

    public AuthService(IUserSessionService sessions) => _sessions = sessions;

    public string? SignIn(string userId, string applicationBaseUrl)
    {
        return _sessions.CreateSession(userId, applicationBaseUrl);
    }
}

Set a session cookie using the platform cookie name constant:

public void SetSessionCookie(HttpResponse response, string sessionId)
{
    response.Cookies.Append(
        UserSessionConstants.SessionCookieName,
        sessionId,
        new CookieOptions
        {
            HttpOnly = true,
            Secure = true,
            SameSite = SameSiteMode.Lax,
            Expires = DateTimeOffset.UtcNow.AddHours(12)
        });
}

Validate a session in middleware

public class SessionValidationMiddleware
{
    private readonly RequestDelegate _next;

    public SessionValidationMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(
        HttpContext context,
        IUserSessionService sessionService)
    {
        string? sessionId = context.Request.Cookies[UserSessionConstants.SessionCookieName];
        string? userId = context.User.FindFirst("sub")?.Value;
        string baseUrl = $"{context.Request.Scheme}://{context.Request.Host}";

        if (string.IsNullOrEmpty(sessionId)
            || string.IsNullOrEmpty(userId)
            || !sessionService.ValidateSession(sessionId, userId, baseUrl))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return;
        }

        await _next(context);
    }
}

Register the middleware:

app.UseMiddleware<SessionValidationMiddleware>();

Log out and revoke a session

public IActionResult Logout(
    HttpRequest request,
    HttpResponse response,
    IUserSessionService sessionService)
{
    string? sessionId = request.Cookies[UserSessionConstants.SessionCookieName];
    string baseUrl = $"{request.Scheme}://{request.Host}";
    string? environment = sessionService.GetEnvironmentFromBaseUrl(baseUrl);

    if (!string.IsNullOrEmpty(sessionId) && !string.IsNullOrEmpty(environment))
    {
        sessionService.RevokeSession(sessionId, environment);
    }

    response.Cookies.Delete(UserSessionConstants.SessionCookieName);
    return Redirect("/");
}

Use the Redis provider with managed identity

builder.Services.AddUserSessionServices(options =>
{
    options.Provider = SessionStoreProviderType.Redis;
    options.SessionExpiryHours = 8;
    options.Redis.ConnectionString = "<your-redis-host>:6380";
    options.Redis.UseManagedIdentity = true;
    options.Redis.ManagedIdentityClientId = "<optional-user-assigned-client-id>";
    options.Redis.SessionKeyPrefix = "i2e:session:";
    options.Redis.UserSessionKeyPrefix = "i2e:user-session:";
});

Look up session details

UserSessionInfo? session = sessionService.GetSession(sessionId);
if (session is { IsActive: true } && session.ExpiresUtc > DateTime.UtcNow)
{
    Console.WriteLine($"User {session.UserId} in {session.Environment}, expires {session.ExpiresUtc:u}");
}

Configuration reference

All options live on UserSessionOptions (configuration section: UserSession).

Option Default Description
Provider Sql Sql or Redis
SessionExpiryHours 12 Session lifetime in hours
MemoryCacheDurationSeconds 600 In-memory cache TTL (seconds)
SessionCacheKeyPrefix i2eSession: Prefix for memory cache keys
InsightsDomainSuffix .insights2execution.com Stripped from host when resolving environment

SQL options (UserSession:Sql)

Option Default
ConnectionString (required)
CreateSessionProcedure SIPF_spCreateUserSession
GetSessionProcedure SIPF_spGetUserSession
GetActiveSessionIdProcedure SIPF_spGetActiveUserSessionId
RevokeSessionProcedure SIPF_spRevokeUserSession

Redis options (UserSession:Redis)

Option Default
ConnectionString (required)
UseManagedIdentity false
ManagedIdentityClientId null
SessionKeyPrefix i2e:session:
UserSessionKeyPrefix i2e:user-session:

API overview

Method Description
CreateSession(userId, baseUrl) Creates or reuses an active session; environment is derived from baseUrl
GetSession(sessionId) Returns session from memory cache or backing store
GetActiveSessionId(userId, environment) Returns the active session id for a user/environment
ValidateSession(sessionId, userId, baseUrl) Validates session ownership, expiry, and environment
RevokeSession(sessionId, environment) Revokes in the store and removes from memory cache
RemoveSessionFromMemory(sessionId) Clears the in-memory cache entry only
GetEnvironmentFromBaseUrl(baseUrl) Parses host/authority into environment name

Model: UserSessionInfo exposes UserId, Environment, CreatedUtc, LastActiveUtc, ExpiresUtc, and IsActive.


Architecture

┌─────────────────┐     ┌──────────────────────┐     ┌─────────────────────┐
│  Your app       │────▶│  IUserSessionService │────▶│  ISessionMemoryCache │
│  (controllers,  │     │  (UserSessionService)│     │  (short-lived cache) │
│   middleware)   │     └──────────┬───────────┘     └─────────────────────┘
└─────────────────┘                │
                                   ▼
                        ┌──────────────────────┐
                        │ IUserSessionStoreFactory │
                        └──────────┬───────────┘
                    ┌──────────────┴──────────────┐
                    ▼                             ▼
           SqlUserSessionStore            RedisUserSessionStore
           (stored procedures)          (Redis keys + TTL)

Project layout

SEyc.Services.Platform.UserSession/
├── Abstractions/          # IUserSessionService, IUserSessionStore, …
├── DependencyInjection/   # AddUserSessionServices
├── Factories/             # Store provider selection
├── Infrastructure/        # SQL repository, Redis connection, memory cache
├── Models/                # UserSessionInfo
├── Options/               # UserSessionOptions and provider settings
├── Services/              # UserSessionService
└── Stores/                # SqlUserSessionStore, RedisUserSessionStore

Documentation

This README is the primary package documentation and is published to the NuGet package details page via PackageReadmeFile. For platform-wide standards, refer to your team’s I2e Platform wiki and release documentation in Azure DevOps.


Feedback and support

We welcome bug reports, feature requests, and questions about integrating this library.

When filing an issue, please include:

  • Package version (UserSessionService.Platform x.y.z)
  • Provider type (Sql or Redis)
  • Relevant configuration (redact connection strings and secrets)
  • Expected vs actual behavior and logs if available

Contributing

Contributions are made through the I2e Platform repository on Azure DevOps.

  1. Create a branch from the current release or development branch your team uses (e.g. Release/2026.x.x).

  2. Make focused changes in Services/Platform/SEyc.Services.Platform.UserSession.

  3. Update README.md if you change public API, configuration, or setup steps.

  4. Bump the package version in SEyc.Services.Platform.UserSession.csproj for any published NuGet change.

  5. Open a pull request in Azure DevOps Repos and link the related work item.

  6. Pack locally to verify the NuGet package:

    dotnet pack SEyc.Services.Platform.UserSession.csproj -c Release
    
  7. After merge, publish the .nupkg to the nuget.

Transitive dependencies

This package depends on platform libraries and Microsoft extensions, including:

Azure.Identity, KeyVaultLibrary.Platform, Microsoft.Azure.StackExchangeRedis, Microsoft.Data.SqlClient, Microsoft.Extensions.*, and StackExchange.Redis. See the .csproj for pinned versions.


License

This project is licensed under the MIT License. See the MIT license for details.


Maintained by: SEyc / SRAI Platform team
Package ID: UserSessionService.Platform

Product Compatible and additional computed target framework versions.
.NET 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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0.4 798 6/23/2026
1.0.0.3 108 6/22/2026
1.0.0.2 125 6/22/2026
1.0.0.1 116 6/22/2026
1.0.0 126 6/19/2026