第三方服务的密钥(AppSecret、API Key、OAuth Token)需要安全地存储、解析和注入。Core 包提供了一套凭据模型,让密钥来源与厂商实现解耦。
模型
IntegrationCredential
凭据快照模型,不可变:
public sealed class IntegrationCredential{ public IntegrationCredentialKey Key { get; } public string Value { get; } // 实际密钥值 public DateTimeOffset? ExpiresAt { get; } public IReadOnlyDictionary<string, string> Metadata { get; }}IntegrationCredentialKey 由 Domain + ProviderId + CredentialName 组合标识。
IIntegrationCredentialStore
同步写入/删除接口,适合在应用启动时预加载凭据:
public interface IIntegrationCredentialStore{ void Set(IntegrationCredentialKey key, IntegrationCredential credential); void Remove(IntegrationCredentialKey key); bool TryGet(IntegrationCredentialKey key, out IntegrationCredential credential);}IIntegrationCredentialResolver
异步解析接口,适合从远程密钥服务按需获取:
public interface IIntegrationCredentialResolver{ Task<IntegrationCredential> ResolveAsync(IntegrationCredentialKey key, CancellationToken ct = default);}InMemoryIntegrationCredentialStore
仅供开发环境使用。生产环境应接入 Vault、KMS 或云密钥服务。
注册
// ① 开发环境使用内存存储(不会自动注册,需显式调用)builder.Services.AddInMemoryIntegrationCredentials();
// ② 生产环境:实现 IIntegrationCredentialStore 或 IIntegrationCredentialResolver,注册自定义实现builder.Services.AddSingleton<IIntegrationCredentialStore, VaultCredentialStore>();安全约定
| 规则 | 原因 |
|---|---|
| 密钥不进入日志 | RequestLogSanitizer 自动脱敏敏感头和字段 |
| 密钥不进入异常详情 | IntegrationException.ProviderMessage 不应包含凭据 |
| 密钥不进入健康检查响应 | Health Check 只报告连接状态 |
| 密钥不进入构造日志 | Options 绑定时不打印完整密钥 |
| 字节数组密钥用后清除 | 签名器 Dispose 时 Array.Clear |