McpHelper.PostgreSQL 1.0.9

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

McpHelper.PostgreSQL

McpHelper PostgreSQL 数据库认证扩展,提供基于 PostgreSQL 数据库的 API Key 认证功能。

功能特性

  • 数据库认证 - 从 PostgreSQL 数据库验证 API Key
  • 认证缓存 - 内置缓存机制,减少数据库查询
  • 认证日志 - 可选的认证日志记录功能
  • 健康检查 - 支持数据库连接健康检查
  • 高性能 - 支持连接池和集群部署

安装

dotnet add package McpHelper.PostgreSQL

依赖

包名 版本 说明
McpHelper.Core 1.0.1 核心库
Npgsql 9.0.3 PostgreSQL 数据库支持

目标框架

  • .NET 10.0

快速开始

1. 基础使用

using McpHelper.Extensions;

var builder = WebApplication.CreateBuilder(args);

// 注册核心中间件
builder.Services.AddMcpHelper();

// 添加 PostgreSQL 认证
builder.Services.AddPostgresAuthentication(options =>
{
    options.ConnectionString = "Host=localhost;Database=mydb;Username=user;Password=pass";
    options.TableName = "api_keys";
    options.KeyColumnName = "key";
});

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

2. 完整配置

builder.Services.AddPostgresAuthentication(options =>
{
    // 数据库连接字符串
    options.ConnectionString = "Host=localhost;Database=mydb;Username=user;Password=pass;Pooling=true;Maximum Pool Size=100";

    // 表和列配置
    options.TableName = "api_keys";
    options.KeyColumnName = "key";

    // 可选:缓存配置
    options.EnableCache = true;
    options.CacheExpirationMinutes = 30;

    // 可选:认证日志
    options.EnableAuthLog = true;
    options.LogTableName = "auth_logs";
});

配置选项

DatabaseOptions

属性 类型 默认值 说明
ConnectionString string 必填 PostgreSQL 连接字符串
TableName string "api_keys" 存储 API Key 的表名
KeyColumnName string "key" API Key 列名
EnableCache bool true 是否启用缓存
CacheExpirationMinutes int 30 缓存过期时间(分钟)
EnableAuthLog bool false 是否启用认证日志
LogTableName string "auth_logs" 认证日志表名

数据库表结构

API Key 表

CREATE TABLE api_keys (
    id SERIAL PRIMARY KEY,
    key VARCHAR(64) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true,
    description VARCHAR(255),
    expires_at TIMESTAMP,
    rate_limit INTEGER DEFAULT 1000
);

-- 创建索引
CREATE INDEX idx_api_keys_key ON api_keys(key);
CREATE INDEX idx_api_keys_is_active ON api_keys(is_active);

-- 插入示例数据
INSERT INTO api_keys (key, description) VALUES
    ('your-api-key-1', 'Development Key'),
    ('your-api-key-2', 'Production Key');

认证日志表(可选)

CREATE TABLE auth_logs (
    id SERIAL PRIMARY KEY,
    key VARCHAR(64) NOT NULL,
    success BOOLEAN NOT NULL,
    ip_address VARCHAR(45),
    user_agent VARCHAR(500),
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引(用于查询优化)
CREATE INDEX idx_auth_logs_timestamp ON auth_logs(timestamp);
CREATE INDEX idx_auth_logs_key ON auth_logs(key);

-- 分区表(可选,用于大量日志)
CREATE TABLE auth_logs_partitioned (
    id SERIAL,
    key VARCHAR(64) NOT NULL,
    success BOOLEAN NOT NULL,
    ip_address VARCHAR(45),
    user_agent VARCHAR(500),
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) PARTITION BY RANGE (timestamp);

使用示例

创建 API Key

using Npgsql;

// 插入新的 API Key
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();

await using var command = connection.CreateCommand();
command.CommandText = @"
    INSERT INTO api_keys (key, description, expires_at)
    VALUES (@key, @description, @expiresAt)";

command.Parameters.AddWithValue("@key", Guid.NewGuid().ToString("N"));
command.Parameters.AddWithValue("@description", "My API Key");
command.Parameters.AddWithValue("@expiresAt", DateTime.UtcNow.AddDays(30));

await command.ExecuteNonQueryAsync();

验证 API Key

认证由中间件自动处理,只需在请求头中添加:

X-Api-Key: your-api-key

完整示例项目

参见 McpHelper.Example.PostgresAuth

连接字符串配置

基础连接字符串

Host=localhost;Database=mydb;Username=user;Password=pass

生产环境推荐配置

Host=localhost;Database=mydb;Username=user;Password=pass;
Pooling=true;
Maximum Pool Size=100;
Minimum Pool Size=5;
Connection Lifetime=300;
Connection Idle Lifetime=60;
Keepalive=30;
Command Timeout=30;

连接字符串参数说明

参数 说明 推荐值
Pooling 启用连接池 true
Maximum Pool Size 最大连接数 100
Minimum Pool Size 最小连接数 5
Connection Lifetime 连接最大生命周期(秒) 300
Keepalive 保持连接活跃(秒) 30
Command Timeout 命令超时(秒) 30

认证缓存

启用缓存后,验证通过的 API Key 会被缓存:

  • 缓存时间:默认 30 分钟
  • 自动刷新:缓存过期后自动重新查询
  • 内存存储:使用内存缓存,重启后清空
  • 分布式缓存:可扩展为 Redis 等分布式缓存

认证日志

启用日志后,每次认证尝试都会记录:

字段 说明
key 使用的 API Key(脱敏)
success 是否认证成功
ip_address 客户端 IP 地址
user_agent 客户端 User-Agent
timestamp 认证时间

健康检查

PostgreSQL 认证扩展会自动注册数据库连接工厂:

builder.Services.AddHealthChecks()
    .AddNpgSql(connectionString, name: "postgres-auth");

性能优化建议

数据库层面

  1. 创建合适的索引

    CREATE INDEX idx_api_keys_key ON api_keys(key);
    CREATE INDEX idx_api_keys_is_active ON api_keys(is_active) WHERE is_active = true;
    
  2. 定期清理日志

    DELETE FROM auth_logs WHERE timestamp < NOW() - INTERVAL '30 days';
    
  3. 使用连接池:确保连接字符串中启用 Pooling=true

应用层面

  1. 启用缓存:减少数据库查询
  2. 调整缓存时间:根据安全需求调整
  3. 监控连接池:确保连接池大小合适

与其他认证方式对比

认证方式 适用场景 优点 缺点
API Key(内置) 少量固定 Key 配置简单 不支持动态管理
SQLite 中小型应用 轻量级、无外部依赖 单文件限制
PostgreSQL 大型应用 高性能、支持集群 需要外部数据库

相关项目

  • McpHelper.Core - 核心库
  • McpHelper.SQLite - SQLite 数据库认证扩展

许可证

MIT License

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.9 119 4/19/2026
1.0.8 104 4/5/2026
1.0.7 108 4/4/2026
1.0.6 112 4/3/2026
1.0.5 102 4/3/2026
1.0.4 102 4/3/2026
1.0.3 107 4/3/2026
1.0.1 101 4/3/2026
1.0.0 109 4/3/2026