Skip to content

Config

Config

go
type Config struct {
    SecretKey       string
    SigningKey      any
    VerificationKey any
    SigningMethod   SigningMethod

    AccessTokenTTL    time.Duration
    RefreshTokenTTL   time.Duration
    Issuer            string
    ExpectedAudience  string
    RequireExpiration bool
    ClockSkew         time.Duration

    Blacklist BlacklistConfig

    EnableRateLimit bool
    RateLimitRate   int
    RateLimitWindow time.Duration
    RateLimiter     RateLimitProvider

    Clock ClockProvider
}

JWT Processor 的统一配置。零值字段会在 New() 中自动填充默认值(通过 normalizeConfig)。

自动填充规则

  • RateLimitRateRateLimitWindow 仅在 EnableRateLimit = true 时填充
  • 内置黑名单存储的 EnableAutoCleanup 始终强制为 true(防止无限增长)
  • SecretKeySigningKeyVerificationKey 不会自动填充,必须手动设置
struct

字段

字段类型默认值说明
SecretKeystringHMAC 密钥(至少 32 字节)
SigningKeyany非对称算法私钥 (*rsa.PrivateKey*ecdsa.PrivateKey)
VerificationKeyany非对称算法公钥(可选,默认使用 SigningKey)
SigningMethodSigningMethodHS256签名算法
AccessTokenTTLtime.Duration15m访问令牌有效期
RefreshTokenTTLtime.Duration168h刷新令牌有效期
Issuerstring"jwt-service"签发者
ExpectedAudiencestring期望的受众(可选)
RequireExpirationboolfalsetrue 时拒绝缺少 exp 声明的令牌(返回 ErrExpirationRequired
ClockSkewtime.Duration0exp/nbf 的时钟偏移容忍度(容忍签发方与验证方的时钟漂移);负值会被 Validate() 拒绝
BlacklistBlacklistConfig黑名单配置
EnableRateLimitboolfalse启用限流
RateLimitRateint100窗口内最大请求数
RateLimitWindowtime.Duration1m限流窗口
RateLimiterRateLimitProvider自定义限流器(可选)
ClockClockProviderSystemClock{}时钟提供者

方法

方法签名说明
Validatefunc (c *Config) Validate() error验证配置有效性

Validate() 检查项:

检查项说明
签名密钥HMAC 需 SecretKey ≥32 字节且非弱密钥;RSA/ECDSA 需正确类型的 SigningKey;ECDSA 需曲线匹配;VerificationKey 需匹配算法公钥类型
TTL 有效性AccessTokenTTLRefreshTokenTTL 必须为正数
TTL 顺序AccessTokenTTL 必须小于 RefreshTokenTTL
ClockSkewClockSkew 不可为负值
签名算法必须为内置支持的 12 种算法之一
黑名单内置存储时 MaxSize 和 CleanupInterval 必须为正数

BlacklistConfig

go
type BlacklistConfig struct {
    CleanupInterval   time.Duration
    MaxSize           int
    EnableAutoCleanup bool
    Store             BlacklistStore
}

黑名单配置。

struct

字段

字段类型默认值说明
CleanupIntervaltime.Duration5m过期清理间隔(仅内置存储时有效)
MaxSizeint100000内存存储最大条目数(仅内置存储时有效)
EnableAutoCleanupbooltrue自动清理过期条目(仅内置存储时有效)
StoreBlacklistStore自定义存储后端(设置后其他字段被忽略)