UserSessionService.Platform
1.0.0
See the version list below for details.
dotnet add package UserSessionService.Platform --version 1.0.0
NuGet\Install-Package UserSessionService.Platform -Version 1.0.0
<PackageReference Include="UserSessionService.Platform" Version="1.0.0" />
<PackageVersion Include="UserSessionService.Platform" Version="1.0.0" />
<PackageReference Include="UserSessionService.Platform" />
paket add UserSessionService.Platform --version 1.0.0
#r "nuget: UserSessionService.Platform, 1.0.0"
#:package UserSessionService.Platform@1.0.0
#addin nuget:?package=UserSessionService.Platform&version=1.0.0
#tool nuget:?package=UserSessionService.Platform&version=1.0.0
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?
- Requirements
- Installation
- Getting started
- Usage examples
- Configuration reference
- API overview
- Architecture
- Documentation
- Feedback and support
- Contributing
- License
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_spCreateUserSessionSIPF_spGetUserSessionSIPF_spGetActiveUserSessionIdSIPF_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();
Step 2 — Bind from configuration (recommended)
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.Platformx.y.z) - Provider type (
SqlorRedis) - 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.
Create a branch from the current release or development branch your team uses (e.g.
Release/2026.x.x).Make focused changes in
Services/Platform/SEyc.Services.Platform.UserSession.Update
README.mdif you change public API, configuration, or setup steps.Bump the package version in
SEyc.Services.Platform.UserSession.csprojfor any published NuGet change.Open a pull request in Azure DevOps Repos and link the related work item.
Pack locally to verify the NuGet package:
dotnet pack SEyc.Services.Platform.UserSession.csproj -c ReleaseAfter merge, publish the
.nupkgto 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 | Versions 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. |
-
net10.0
- Azure.Identity (>= 1.21.0)
- KeyVaultLibrary.Platform (>= 2.0.0)
- Microsoft.Azure.StackExchangeRedis (>= 3.2.1)
- Microsoft.Data.SqlClient (>= 7.0.0)
- Microsoft.Extensions.Caching.Memory (>= 10.0.6)
- Microsoft.Extensions.DependencyInjection (>= 10.0.6)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.6)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.6)
- Microsoft.Extensions.Options (>= 10.0.6)
- StackExchange.Redis (>= 2.8.24)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.