ApiFeatures.Authentications.Sessions.Postgresqls
9.0.1
dotnet add package ApiFeatures.Authentications.Sessions.Postgresqls --version 9.0.1
NuGet\Install-Package ApiFeatures.Authentications.Sessions.Postgresqls -Version 9.0.1
<PackageReference Include="ApiFeatures.Authentications.Sessions.Postgresqls" Version="9.0.1" />
<PackageVersion Include="ApiFeatures.Authentications.Sessions.Postgresqls" Version="9.0.1" />
<PackageReference Include="ApiFeatures.Authentications.Sessions.Postgresqls" />
paket add ApiFeatures.Authentications.Sessions.Postgresqls --version 9.0.1
#r "nuget: ApiFeatures.Authentications.Sessions.Postgresqls, 9.0.1"
#:package ApiFeatures.Authentications.Sessions.Postgresqls@9.0.1
#addin nuget:?package=ApiFeatures.Authentications.Sessions.Postgresqls&version=9.0.1
#tool nuget:?package=ApiFeatures.Authentications.Sessions.Postgresqls&version=9.0.1
ApiFeatures.Authentications.Sessions.Postgresqls
PostgreSQL database implementation for the Session Authentication feature using Entity Framework Core.
Overview
This package provides PostgreSQL storage support for the ApiFeatures.Authentications.Sessions library. It separates PostgreSQL-specific concerns from the core session authentication functionality and uses Entity Framework Core for data access.
The package does not bundle EF Core migrations. The DbContext model is parameterized — column names are supplied by the consumer through an ISessionEntityOptions implementation registered in DI — so any baked-in migration would lock consumers to one naming scheme. Each consumer authors their own migration in their own project; the DbContext automatically points EF at the consumer's assembly (the one containing the ISessionEntityOptions implementation) via MigrationsAssembly(...).
Installation
dotnet add package ApiFeatures.Authentications.Sessions.Postgresqls
Usage
1. Implement ISessionEntityOptions
ISessionEntityOptions decides the column names used by the DbContext. There is no built-in default — every consumer must provide one. The simplest implementation just returns the entity property names:
using ApiFeatures.Authentications.Sessions.Postgresqls.Models.Options;
public class MySessionEntityOptions : ISessionEntityOptions
{
public string GetIdColumnName() => "Id";
public string GetKeyColumnName() => "Key";
public string GetUsernameColumnName() => "Username";
public string GetMetadataColumnName() => "Metadata";
public string GetExpiryTimeColumnName() => "ExpiryTime";
public string GetCreatedTimeColumnName() => "CreatedTime";
}
2. Register the feature
using ApiFeatures.Authentications.Sessions.Extensions;
using ApiFeatures.Authentications.Sessions.Postgresqls.Extensions;
using ApiFeatures.Authentications.Sessions.Postgresqls.Models.Options;
var builder = WebApplication.CreateBuilder(args);
// ISessionEntityOptions is resolved from DI by the DbContext factory.
// Register your concrete implementation before AddSessionAuthenticationFeature.
builder.Services.AddSingleton<ISessionEntityOptions, MySessionEntityOptions>();
var postgresOptions = new PostgresSessionAuthenticationDatabaseOptions
{
ConnectionString = "Host=localhost;Database=SessionAuthDb;Username=postgres;Password=yourpassword",
Schema = "public",
TableName = "sessions"
};
var sessionAuthOptions = new AddSessionAuthenticationFeatureOptions
{
Scheme = "Session"
};
sessionAuthOptions
.WithPostgresDatabase(postgresOptions)
.WithBusinessLogic<YourBusinessLogic>();
// ... other configurations
builder.Services.AddSessionAuthenticationFeature(sessionAuthOptions);
3. Generate your migration
Add a design-time factory in your project so the EF Core tooling can instantiate PostgresSessionDatabaseContext with your ISessionEntityOptions. Build the factory's configuration from the same sources Program.cs does — that way dotnet ef database update hits the same database your app would:
using ApiFeatures.Authentications.Sessions.Postgresqls.Databases;
using ApiFeatures.Authentications.Sessions.Postgresqls.Models.Options;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
public class PostgresSessionDatabaseContextFactory : IDesignTimeDbContextFactory<PostgresSessionDatabaseContext>
{
public PostgresSessionDatabaseContext CreateDbContext(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{environment}.json", optional: true)
.AddEnvironmentVariables();
if (string.Equals(environment, "Development", StringComparison.OrdinalIgnoreCase))
{
builder.AddUserSecrets<Program>(optional: true);
}
var configuration = builder.Build();
var connectionString = configuration.GetConnectionString("Default")
?? throw new InvalidOperationException("Connection string 'Default' is not configured.");
var options = new PostgresSessionAuthenticationDatabaseOptions
{
ConnectionString = connectionString,
Schema = "public",
TableName = "sessions"
};
return new PostgresSessionDatabaseContext(options, new MySessionEntityOptions());
}
}
If you only run
dotnet ef migrations add(notdatabase update), the connection string is unused — EF inspects only the provider. The configuration plumbing above is fordatabase updatefrom the CLI.
Then generate the migration. The DbContext auto-sets MigrationsAssembly to the assembly that contains your ISessionEntityOptions implementation, so the migrations land in your project, not in this library:
dotnet ef migrations add InitialMigration `
--project <your-project> `
--startup-project <your-project> `
--context PostgresSessionDatabaseContext `
--output-dir Migrations/Sessions
The generated SQL will use whatever column names your ISessionEntityOptions returns.
3a. Apply the migration from the CLI (optional)
If you'd rather apply migrations through CI/CD or by hand instead of at app startup:
dotnet ef database update `
--project <your-project> `
--startup-project <your-project> `
--context PostgresSessionDatabaseContext
Skip this step if you call app.UsePostgresDatabase() at runtime — that already applies pending migrations.
4. Apply the migration at startup
UsePostgresDatabase() calls Database.Migrate() against the consumer's migrations, creating the database if missing and bringing the schema up to the latest migration:
var app = builder.Build();
app.UsePostgresDatabase(); // creates the database + applies pending migrations
app.UseSessionAuthentication();
app.Run();
Skip it if your project provisions the schema another way — for example, when you ship raw SQL with your deploy or run dotnet ef database update from CI.
Managing the schema
The recommended path is steps 3 and 4 above: generate a migration in your project, then call UsePostgresDatabase() to apply it at startup. As alternatives:
dotnet ef database updatefrom CI — run the same migrations through the CLI as part of your deploy pipeline instead of at app startup. In that case, do not callUsePostgresDatabase().- Raw SQL — manage the schema by hand using the reference shape below. Replace the bracketed column names with whatever your
ISessionEntityOptionsreturns. The shape below assumesId, Key, Username, Metadata, ExpiryTime, CreatedTime:
CREATE TABLE sessions (
"<Id>" uuid NOT NULL PRIMARY KEY,
"<Key>" character varying(500) NOT NULL,
"<Username>" character varying(255) NOT NULL,
"<Metadata>" text NULL,
"<ExpiryTime>" timestamp with time zone NULL,
"<CreatedTime>" timestamp with time zone NOT NULL
);
CREATE UNIQUE INDEX "IX_Session_Key" ON sessions ("<Key>");
CREATE INDEX "IX_Session_Username" ON sessions ("<Username>");
CREATE INDEX "IX_Session_ExpiryTime" ON sessions ("<ExpiryTime>") WHERE "<ExpiryTime>" IS NOT NULL;
The Metadata column stores the SessionMetadata value as JSON; the runtime serializes/deserializes on read and write.
Customizing the schema (PostgreSQL namespace)
The DbContext does not call HasDefaultSchema(). The sessions table lands wherever the connection's search_path resolves first:
ConnectionString = "Host=...;Database=...;Username=...;Password=...;Search Path=myschema"
Make sure the schema exists (CREATE SCHEMA myschema) before you call UsePostgresDatabase() or run any migration. The library does not issue EnsureSchema.
Features
- PostgresSessionService: PostgreSQL implementation of
ISessionServiceusing EF Core - PostgresSessionDatabaseContext: EF Core DbContext with configurable table and column names
- PostgresSessionAuthenticationDatabaseOptions: Configuration options for PostgreSQL connection
- ISessionEntityOptions: Per-column name customization, supplied via DI. Also drives
MigrationsAssembly(...)auto-detection so migrations land in the consumer project. - Extension Methods: Fluent API for easy configuration
- Automatic Indexing: Optimized indexes on Key, Username, and ExpiryTime columns
- JSON metadata column:
SessionMetadatais serialized to a singletextcolumn via an EF Core value converter
Configuration Options
PostgresSessionAuthenticationDatabaseOptions
- ConnectionString (required): PostgreSQL connection string. Use
Search Path=...to control which schema thesessionstable is placed in. - Schema (required): Schema used for the EF Core migration-history table (
__EFMigrationsHistory) when consumers ship their own migrations. Not used byUsePostgresDatabase(). - TableName (optional): Table name for sessions (default:
"sessions"). - MigrationTable (optional): Migration history table name. If not set, EF Core uses its default
__EFMigrationsHistory.
ISessionEntityOptions
Interface — consumers must implement all six methods (GetIdColumnName, GetKeyColumnName, GetUsernameColumnName, GetMetadataColumnName, GetExpiryTimeColumnName, GetCreatedTimeColumnName) and register the concrete in DI (AddSingleton, AddScoped, or AddTransient).
The DbContext also uses the implementation's assembly to set MigrationsAssembly(...) automatically, so EF places your migrations in the same project where ISessionEntityOptions lives. You don't need to configure this yourself.
Example with Custom Migration Table
var postgresOptions = new PostgresSessionAuthenticationDatabaseOptions
{
ConnectionString = "Host=localhost;Database=SessionAuthDb;Username=postgres;Password=yourpassword",
Schema = "public",
TableName = "sessions",
MigrationTable = "CustomMigrationHistory" // Optional: use custom migration table
};
Dependencies
- ApiFeatures.Authentications.Sessions
- Microsoft.EntityFrameworkCore (9.0.0)
- Npgsql.EntityFrameworkCore.PostgreSQL (9.0.2)
- BusinessFeatures.Cores
Performance Considerations
- The package uses
AsNoTracking()for read operations to improve performance - Proper indexes are configured on Key, Username, and ExpiryTime
- Connection pooling is handled by Npgsql
- Consider using a connection pool size appropriate for your workload
License
[Your License Here]
| Product | Versions 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. |
-
net9.0
- ApiFeatures.Authentications.Sessions (>= 9.0.0)
- BusinessFeatures.Cores (>= 9.0.1)
- Microsoft.EntityFrameworkCore (>= 9.0.0)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 9.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.