ApiFeatures.Authentications.Sessions 9.0.0

dotnet add package ApiFeatures.Authentications.Sessions --version 9.0.0
                    
NuGet\Install-Package ApiFeatures.Authentications.Sessions -Version 9.0.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.0.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.0.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.0.0
                    
#r "nuget: ApiFeatures.Authentications.Sessions, 9.0.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.0.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.0.0
                    
Install as a Cake Addin
#tool nuget:?package=ApiFeatures.Authentications.Sessions&version=9.0.0
                    
Install as a Cake Tool

ApiFeatures.Authentications.Sessions

A comprehensive session-based authentication module for ASP.NET Core applications with MongoDB and PostgreSQL support, providing flexible session management with cookie or body-based responses.

Features

  • Multiple Database Support: MongoDB and PostgreSQL with Entity Framework Core
  • Session Storage Options: In-Memory and Redis caching for session data
  • Flexible Response Modes: Return session keys in HTTP-only cookies or response body
  • Cookie Security: Configurable HttpOnly, Secure, and SameSite attributes
  • Session Validation: Middleware automatically validates sessions from cookies or Authorization headers
  • Session Metadata: Track device and browser information
  • Session Expiration: Built-in expiration checking with UTC timestamps
  • FluentValidation: Input validation with configurable constraints
  • Built on .NET 9: Modern async/await patterns with keyed services

Installation

Add project reference:

dotnet add reference path/to/ApiFeatures.Authentications.Sessions.csproj

Quick Start

1. Configuration

MongoDB Configuration (secrets.json or appsettings.json):
{
  "Authentication": {
    "Session": {
      "Scheme": "Session",
      "Database": {
        "Type": "Mongo",
        "ConnectionString": "mongodb://localhost:27017",
        "DatabaseName": "SessionDb",
        "Collection": {
          "Sessions": "sessions"
        }
      },
      "ResponseLocation": {
        "CookieName": "SessionToken",
        "SameSite": "None",
        "HttpOnly": true,
        "Secure": false
      }
    }
  }
}
PostgreSQL Configuration:
{
  "Authentication": {
    "Session": {
      "Scheme": "Session",
      "Database": {
        "Type": "Postgres",
        "ConnectionString": "Host=localhost;Database=SessionDb;Username=postgres;Password=password",
        "Schema": "public",
        "TableName": "sessions"
      }
    }
  }
}
Session Storage Configuration

Session storage defines how session data is cached in memory. This is separate from the database configuration.

In-Memory Storage (Default):
{
  "Authentication": {
    "Session": {
      "Storage": {
        "Type": "InMemory"
      }
    }
  }
}
Redis Storage:
{
  "Authentication": {
    "Session": {
      "Storage": {
        "Type": "Redis",
        "Host": "localhost",
        "Port": 6379,
        "Password": "your_redis_password",
        "Username": "default",
        "InstanceName": "MyApp:",
        "Database": 0,
        "ConnectTimeout": 5000,
        "SyncTimeout": 5000,
        "AbortOnConnectFail": false,
        "Ssl": false
      }
    }
  }
}

Redis Storage Properties:

Property Type Default Description
Host string (required) Redis server address (e.g., "localhost", "redis.example.com")
Port int 6379 Redis server port
Password string? null Password for Redis authentication
Username string? null Username for Redis ACL authentication (Redis 6+)
InstanceName string? null Optional prefix for all keys (e.g., "MyApp:" → "MyApp:session:key123")
Database int 0 Redis database number (0-15)
ConnectTimeout int 5000 Connection timeout in milliseconds
SyncTimeout int 5000 Sync operation timeout in milliseconds
AbortOnConnectFail bool false Whether to abort on connection failure or retry
Ssl bool false Whether to use SSL/TLS (required for Azure Redis Cache)

2. Implement Business Logic

Create a class implementing ISessionFeatureBusinessLogic:

using ApiFeatures.Authentications.Sessions.Services.Interfaces;

public class MySessionBusinessLogic : ISessionFeatureBusinessLogic
{
    public async Task<bool> IsAuthenticationValidAsync(
        string username, 
        string password, 
        CancellationToken cancellationToken = default)
    {
        // Validate credentials against your user database
        var user = await _userRepository.GetByUsernameAsync(username, cancellationToken);
        if (user == null) return false;

        return VerifyPassword(user, password);
    }
}

3. Register Services in Program.cs

using ApiFeatures.Authentications.Sessions.Extensions;
using ApiFeatures.Authentications.Sessions.Models;
using ApiFeatures.Authentications.Sessions.Models.Options;
using BusinessFeatures.Cores.Contexts;

var builder = WebApplication.CreateBuilder(args);

// Add session authentication
var sessionOptions = builder.Configuration
    .GetSection("Authentication:Session")
    .Get<SessionAuthenticationOptions>();

var featureOptions = new AddSessionAuthenticationFeatureOptions
{
    Scheme = sessionOptions.Scheme,
    Database = sessionOptions.Database,
    ResponseLocation = sessionOptions.ResponseLocation,
    Storage = sessionOptions.Storage  // Optional: InMemory or Redis
}
.WithDateTimeContext<DateTimeContext>()
.WithDateTimeOffsetContext<DateTimeOffsetContext>()
.WithBusinessLogic<MySessionBusinessLogic>();  // Your business logic

builder.Services.AddSessionAuthenticationFeature(featureOptions);

// Add CORS if frontend is on different origin
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("http://localhost:4200")
            .AllowCredentials()  // Required for cookies
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

var app = builder.Build();

app.UseCors();
app.UseSessionAuthentication();
app.AddSessionAuthenticationEndpoints();

app.Run();

API Endpoints

POST /api/authentication/session

Create a new session (login).

Request:

{
  "username": "user@example.com",
  "password": "SecurePassword123!",
  "device": {
    "name": "iPhone 15 Pro",
    "model": "iPhone15,2"
  },
  "browser": {
    "name": "Safari",
    "version": "17.0"
  }
}

Response (Body Mode):

{
  "accessToken": "base64_encoded_session_key",
  "type": "Session",
  "expiryTime": null
}

Response (Cookie Mode):

  • Session key set in HTTP-only cookie
  • Returns empty object: {}

DELETE /api/authentication/session

Delete current session (logout).

Headers:

Authorization: Session <session_key>

Response: 204 No Content

Response Modes

Body-Based Sessions (Default)

Session key returned in response body. Client stores it (e.g., localStorage) and sends in Authorization header.

Configuration:

{
  "ResponseLocation": null  // or omit this property
}

Client Usage:

// Login
const response = await fetch('/api/authentication/session', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username, password, device })
});
const { accessToken } = await response.json();
localStorage.setItem('sessionToken', accessToken);

// Authenticated request
fetch('/api/protected', {
  headers: { 'Authorization': `Session ${accessToken}` }
});

Session key stored in HTTP-only cookie. Automatically sent by browser.

Configuration:

{
  "ResponseLocation": {
    "CookieName": "SessionToken",
    "SameSite": "None",
    "HttpOnly": true,
    "Secure": false
  }
}

Client Usage:

// Login
await fetch('/api/authentication/session', {
  method: 'POST',
  credentials: 'include',  // Required for cookies
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username, password, device })
});

// Authenticated request - cookie sent automatically
fetch('/api/protected', {
  credentials: 'include'
});

SameSite Modes

Mode Description Use Case
Strict Cookie only sent on same-site requests Same domain (e.g., app.example.com → api.example.com)
Lax Cookie sent on same-site + top-level navigation Default, good balance
None Cookie sent on all requests including cross-origin Different origins (e.g., localhost:4200 → localhost:5001)

⚠️ Important: SameSite=None requires Secure=true (HTTPS)

Development vs Production

Development (HTTP):

{
  "SameSite": "None",
  "Secure": false
}

Production (HTTPS):

{
  "SameSite": "None",
  "Secure": true
}

Database vs Storage Configuration

Understanding the Difference

This module uses two separate configuration concepts:

Database - Persistent storage for session entities (MongoDB or PostgreSQL)

  • Stores complete session records with metadata
  • Provides long-term persistence
  • Used for session creation, deletion, and querying
  • Required for the session authentication feature

Storage - Fast in-memory caching for session validation (InMemory or Redis)

  • Caches session data for quick authentication
  • Optional but recommended for high-performance scenarios
  • Reduces database queries during request authentication
  • Can be configured independently from the database

Example: MongoDB Database + Redis Storage

{
  "Authentication": {
    "Session": {
      "Database": {
        "Type": "Mongo",
        "ConnectionString": "mongodb://localhost:27017",
        "DatabaseName": "SessionDb"
      },
      "Storage": {
        "Type": "Redis",
        "Host": "localhost",
        "Port": 6379
      }
    }
  }
}

This configuration:

  • Creates/deletes sessions in MongoDB (persistent)
  • Caches session data in Redis (fast authentication)
  • Best of both worlds: durability + performance

Database Configuration

MongoDB

Features:

  • Uses MongoDB.Driver
  • Singleton context for connection pooling
  • Automatic collection creation

Schema:

{
  _id: ObjectId,
  Key: String,
  Username: String,
  Metadata: {
    Device: { Name: String, Model: String },
    Browser: { Name: String, Version: String }
  },
  ExpiryTime: Date,
  CreatedTime: Date
}

PostgreSQL

Features:

  • Uses Entity Framework Core
  • Automatic schema and table creation
  • Filtered indexes for performance

Schema:

CREATE TABLE "public"."sessions" (
    "Id" UUID PRIMARY KEY,
    "Key" VARCHAR(512) NOT NULL,
    "Username" VARCHAR(256) NOT NULL,
    "DeviceName" VARCHAR(512),
    "DeviceModel" VARCHAR(512),
    "BrowserName" VARCHAR(512),
    "BrowserVersion" VARCHAR(512),
    "ExpiryTime" TIMESTAMP WITH TIME ZONE,
    "CreatedTime" TIMESTAMP WITH TIME ZONE NOT NULL
);

CREATE UNIQUE INDEX "IX_Session_Key" ON "public"."sessions" ("Key");
CREATE INDEX "IX_Session_Username" ON "public"."sessions" ("Username");
CREATE INDEX "IX_Session_ExpiryTime" ON "public"."sessions" ("ExpiryTime") 
    WHERE "ExpiryTime" IS NOT NULL;

Validation Constraints

Session entity constraints defined in SessionEntityConstraints:

Property Max Length
Key 512
Username 256
DeviceName 512
DeviceModel 512
BrowserName 512
BrowserVersion 512

Advanced Usage

Custom DateTime Context

public class MyDateTimeContext : IDateTimeContext
{
    public Task<DateTime> GetUtcNowAsync(CancellationToken cancellationToken = default)
    {
        return Task.FromResult(DateTime.UtcNow);
    }
}

var options = new AddSessionAuthenticationFeatureOptions { ... }
    .WithDateTimeContext<MyDateTimeContext>();

Custom Business Logic with Factory

var options = new AddSessionAuthenticationFeatureOptions { ... }
    .WithBusinessLogic(sp => 
    {
        var userRepo = sp.GetRequiredService<IUserRepository>();
        return new MySessionBusinessLogic(userRepo);
    });

Session Expiration

Set expiry time when creating sessions:

var sessionEntity = await sessionService.CreateAsync(
    username,
    metadata,
    expiryTime: DateTime.UtcNow.AddHours(24),
    cancellationToken);

Session Storage Scenarios

When to Use In-Memory Storage

Pros:

  • ✅ Zero configuration required (default)
  • ✅ No external dependencies
  • ✅ Fastest performance for single-server scenarios
  • ✅ Ideal for development and testing

Cons:

  • ❌ Not shared across multiple server instances
  • ❌ Sessions lost on application restart
  • ❌ Limited by server memory

Use Cases:

  • Single-server applications
  • Development environments
  • Small-scale applications with low session volume

When to Use Redis Storage

Pros:

  • ✅ Shared across multiple server instances (load balancing)
  • ✅ Sessions persist across application restarts
  • ✅ Automatic expiration with TTL (Time-To-Live)
  • ✅ High performance with in-memory caching
  • ✅ Scalable for large session volumes

Cons:

  • ❌ Requires Redis server installation/configuration
  • ❌ Additional infrastructure cost
  • ❌ Network latency (minimal)

Use Cases:

  • Production applications with multiple servers
  • Load-balanced environments
  • Microservices architecture
  • Applications requiring session persistence
  • High-traffic applications

Redis Storage Configuration Examples

Local Development:

{
  "Storage": {
    "Type": "Redis",
    "Host": "localhost",
    "Port": 6379
  }
}

Azure Redis Cache:

{
  "Storage": {
    "Type": "Redis",
    "Host": "myapp.redis.cache.windows.net",
    "Port": 6380,
    "Password": "your_access_key",
    "Ssl": true
  }
}

Multi-Tenant with Instance Prefix:

{
  "Storage": {
    "Type": "Redis",
    "Host": "localhost",
    "Port": 6379,
    "InstanceName": "TenantA:",
    "Database": 1
  }
}

Redis with ACL Authentication (Redis 6+):

{
  "Storage": {
    "Type": "Redis",
    "Host": "localhost",
    "Port": 6379,
    "Username": "session_user",
    "Password": "secure_password",
    "Database": 0
  }
}

When frontend (localhost:4200) calls backend (localhost:5001):

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("http://localhost:4200")
            .AllowCredentials()  // Required for cookies
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
});

app.UseCors();

Security Considerations

  1. HTTPS in Production: Always use Secure=true with HTTPS
  2. HttpOnly Cookies: Prevents XSS attacks from stealing session keys
  3. SameSite Protection: Mitigates CSRF attacks
  4. Session Expiration: Set appropriate expiry times
  5. Strong Session Keys: Uses GUID + username + random string (Base64 encoded)
  6. Redis Security:
    • Use password authentication in production
    • Enable SSL/TLS for encrypted connections (Ssl: true)
    • Use Redis ACL for fine-grained access control (Redis 6+)
    • Consider network isolation (VPC/firewall rules)
  7. Database Security:
    • Use encrypted connections (SSL/TLS)
    • Follow principle of least privilege for database users
    • Regularly rotate database credentials

Examples

See the ApiFeatures.Applications.Authentication.Sessions project for a complete working example.

License

[Your License Here]

// Your endpoints here app.MapGet("/api/protected", (HttpContext context) ⇒ { return Results.Ok(new { user = context.User.Identity?.Name }); }) .RequireAuthorization();

app.Run();


## Configuration Options

### Session Location Types

#### HTTP Header
```csharp
options.SessionLocation = new HttpHeaderSessionLocation("X-Session-Key") 
{ 
    Name = "X-Session-Key" 
};

Request Example:

GET /api/protected HTTP/1.1
X-Session-Key: demo-session-key-123
Authorization Header (with Scheme)
options.SessionLocation = new HttpHeaderSessionLocation("Authorization") 
{ 
    Name = "Authorization" 
};
options.Scheme = "Session"; // Optional scheme prefix

Request Example:

GET /api/protected HTTP/1.1
Authorization: Session demo-session-key-123
options.SessionLocation = new CookieSessionLocation("session") 
{ 
    Name = "session" 
};

Request Example:

GET /api/protected HTTP/1.1
Cookie: session=demo-session-key-123
Query String
options.SessionLocation = new QueryStringSessionLocation("sessionKey") 
{ 
    Name = "sessionKey" 
};

Request Example:

GET /api/protected?sessionKey=demo-session-key-123 HTTP/1.1

Session Model

Session

public class Session
{
    public required string Key { get; set; }
    public Guid? UserId { get; set; }
    public string? Username { get; set; }
    public SessionMetadata? Metadata { get; set; }
    public DateTime? ExpiryTime { get; set; }
}

SessionMetadata

public class SessionMetadata
{
    public SessionDevice? Device { get; set; }
    public SessionBrowser? Browser { get; set; }
}

SessionDevice

public class SessionDevice
{
    public string? Name { get; set; }    // e.g., "iPhone 14 Pro"
    public string? Model { get; set; }   // e.g., "iOS 17.0"
}

SessionBrowser

public class SessionBrowser
{
    public string? Name { get; set; }    // e.g., "Chrome"
    public string? Version { get; set; } // e.g., "120.0.6099.109"
}

Advanced Configuration

Multiple Authentication Schemes

var authBuilder = builder.Services.AddAuthentication("SESSION_DEFAULT");

// Header-based session (required authentication)
authBuilder.AddSessionAuthentication("SESSION_HEADER", options =>
{
    options.SessionLocation = new HttpHeaderSessionLocation("X-Session-Key") 
    { 
        Name = "X-Session-Key" 
    };
    options.AllowAnonymous = false;
    options.ValidateSessionAsync = ValidateSessionFromHeader;
    options.BuildAuthenticationPrincipal = BuildPrincipalForHeader;
});

// Cookie-based session (allows anonymous)
authBuilder.AddSessionAuthentication("SESSION_COOKIE", options =>
{
    options.SessionLocation = new CookieSessionLocation("session") 
    { 
        Name = "session" 
    };
    options.AllowAnonymous = true;
    options.ValidateSessionAsync = ValidateSessionFromCookie;
    options.BuildAuthenticationPrincipal = BuildPrincipalForCookie;
    options.BuildAnonymousPrincipal = BuildAnonymousPrincipal;
});

Session Expiration

Sessions with ExpiryTime set will be automatically validated:

var session = new Session
{
    Key = "session-key-123",
    UserId = userId,
    Username = "john.doe",
    ExpiryTime = DateTime.UtcNow.AddDays(7) // Expires in 7 days
};

If the current UTC time exceeds ExpiryTime, the authentication will fail with:

Authentication failed: Session expired at 2026-03-20T12:34:56.789Z

Anonymous Access

When AllowAnonymous = true, requests without a session key will be authenticated as anonymous users:

options.AllowAnonymous = true;

options.BuildAnonymousPrincipal = context =>
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Role, "Anonymous"),
        new Claim("IsAnonymous", "true")
    };
    var identity = new ClaimsIdentity(claims, "SESSION_SCHEME");
    return new ClaimsPrincipal(identity);
};

Sample Application

A complete sample application is available at src/apps/ApiFeatures.Applications.Authentication.Sessions.

Running the Sample

cd src/apps/ApiFeatures.Applications.Authentication.Sessions
dotnet run

Navigate to:

  • Scalar UI: http://localhost:5245/scalar/v1
  • OpenAPI Spec: http://localhost:5245/openapi/v1.json

Demo Sessions

The sample includes pre-configured sessions:

Session Key User ID Username Expiry
demo-session-key-123 00000000-0000-0000-0000-000000000001 demo-user 7 days
admin-session-key-456 00000000-0000-0000-0000-000000000002 admin-user 30 days

Testing Endpoints

Test Authentication (requires session):

curl -H "X-Session-Key: demo-session-key-123" http://localhost:5245/api/ping

Get Demo Sessions (no authentication required):

curl http://localhost:5245/api/sessions

Integration with Session Storage

Example: Database-backed Session Validation

public class SessionRepository
{
    private readonly DbContext _dbContext;

    public async Task<Session?> GetByKeyAsync(string key, CancellationToken cancellationToken)
    {
        var entity = await _dbContext.Sessions
            .Where(s => s.Key == key)
            .FirstOrDefaultAsync(cancellationToken);

        if (entity == null)
            return null;

        return new Session
        {
            Key = entity.Key,
            UserId = entity.UserId,
            Username = entity.Username,
            ExpiryTime = entity.ExpiryTime,
            Metadata = entity.Metadata != null 
                ? JsonSerializer.Deserialize<SessionMetadata>(entity.Metadata)
                : null
        };
    }
}

// In Program.cs
options.ValidateSessionAsync = async (sessionKey, context, cancellationToken) =>
{
    var repo = context.RequestServices.GetRequiredService<SessionRepository>();
    return await repo.GetByKeyAsync(sessionKey, cancellationToken);
};

Example: Redis-backed Session Validation

public class RedisSessionStore
{
    private readonly IConnectionMultiplexer _redis;

    public async Task<Session?> GetAsync(string key)
    {
        var db = _redis.GetDatabase();
        var json = await db.StringGetAsync($"session:{key}");
        
        if (json.IsNullOrEmpty)
            return null;

        return JsonSerializer.Deserialize<Session>(json!);
    }
}

// In Program.cs
options.ValidateSessionAsync = async (sessionKey, context, cancellationToken) =>
{
    var store = context.RequestServices.GetRequiredService<RedisSessionStore>();
    return await store.GetAsync(sessionKey);
};

Architecture

ApiFeatures.Authentications.Sessions/
├── Constants/
│   ├── ServiceKeys.cs
│   ├── SessionLocationTypes.cs
│   ├── SessionStorageTypes.cs
│   └── DatabaseTypes.cs
├── Extensions/
│   └── SessionAuthenticationExtensions.cs
├── Models/
│   ├── AddSessionAuthenticationFeatureOptions.cs
│   ├── Session.cs
│   ├── SessionAuthenticationHandler.cs
│   ├── SessionBrowser.cs
│   ├── SessionDevice.cs
│   ├── SessionLocation.cs
│   ├── SessionMetadata.cs
│   ├── HttpHeaderSessionLocation.cs
│   ├── CookieSessionLocation.cs
│   ├── QueryStringSessionLocation.cs
│   └── Options/
│       ├── SessionAuthenticationSchemeOptions.cs
│       ├── DatabaseOptions.cs
│       ├── MongoSessionAuthenticationDatabaseOptions.cs
│       ├── PostgresSessionAuthenticationDatabaseOptions.cs
│       └── SessionStorages/
│           ├── SessionStorageOptions.cs
│           ├── InMemorySessionStorageOptions.cs
│           └── RedisSessionStorageOptions.cs
├── Services/
│   └── Interfaces/
│       ├── ISessionService.cs
│       ├── ISessionStorage.cs
│       └── ISessionFeatureBusinessLogic.cs
└── Databases/
    ├── SessionDatabaseContext.cs (MongoDB)
    └── PostgresSessionDatabaseContext.cs

Authentication Flow

┌──────────────────────────────────────────┐
│ 1. HTTP Request Received                 │
│    - With session key in configured      │
│      location (header/cookie/query)      │
└──────────────────────────────────────────┘
                   ↓
┌──────────────────────────────────────────┐
│ 2. SessionAuthenticationHandler          │
│    - Extract session key based on        │
│      SessionLocation configuration       │
└──────────────────────────────────────────┘
                   ↓
┌──────────────────────────────────────────┐
│ 3. Validate Session                      │
│    - Call ValidateSessionAsync delegate  │
│    - Check session expiration            │
└──────────────────────────────────────────┘
                   ↓
┌──────────────────────────────────────────┐
│ 4. Build Claims Principal                │
│    - Call BuildAuthenticationPrincipal   │
│    - Create ClaimsIdentity               │
└──────────────────────────────────────────┘
                   ↓
┌──────────────────────────────────────────┐
│ 5. Authentication Success                │
│    - User.Identity.IsAuthenticated = true│
│    - Claims available in endpoints       │
└──────────────────────────────────────────┘

Dependencies

  • Microsoft.AspNetCore.App (Framework reference)
  • BusinessFeatures.Cores (For IDateTimeContext)
  • MongoDB.Driver (Optional - for MongoDB session storage)
  • Npgsql.EntityFrameworkCore.PostgreSQL (Optional - for PostgreSQL session storage)
  • StackExchange.Redis (Optional - for Redis session storage)

Comparison with Entity from Authentication Service

This module uses the Session model which mirrors the SessionEntity from the authentication service:

Property SessionEntity Session (This Module)
Id ✅ (from DefaultEntity) ❌ (Not needed in handler)
Key
UserId
Username
Metadata
ExpiryTime
CreatedTime ✅ (from DefaultEntity) ❌ (Not needed in handler)

The Session model is lightweight and focused on authentication, while SessionEntity is for persistence.

Best Practices

  1. Store session keys securely: Use HTTPS for all production traffic
  2. Implement session rotation: Rotate keys after sensitive operations
  3. Set appropriate expiration: Balance security and user experience
  4. Log authentication events: Track successful and failed authentication attempts
  5. Use strong random keys: Generate cryptographically secure session keys
  6. Clean up expired sessions: Implement background job to remove expired sessions
  7. Choose appropriate storage:
    • Use In-Memory for development and single-server deployments
    • Use Redis for production multi-server environments
    • Configure Redis with password and SSL in production
  8. Database selection:
    • Use MongoDB for flexible schema and high write throughput
    • Use PostgreSQL for ACID compliance and relational integrity
  9. Session metadata: Capture device and browser info for security auditing
  10. Instance prefixes: Use InstanceName in Redis for multi-tenant applications

Contributing

Refer to the main repository's CONTRIBUTING.md for guidelines.

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 was computed.  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.MongoDatabases

Package Description

ApiFeatures.Authentications.Sessions.Postgresqls

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
9.0.0 45 5/7/2026