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
    RejectRefreshAsAccess bool
    RotateRefreshTokens   bool
    ClockSkew             time.Duration

    Blacklist BlacklistConfig

    EnableRateLimit bool
    RateLimitRate   int
    RateLimitWindow time.Duration
    RateLimiter     RateLimitProvider

    Clock ClockProvider
}

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

自动填充规则

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

字段 ​

字段类型默认值说明
SecretKeystring—HMAC 密钥(至少 32 字节)
SigningKeyany—非对称算法私钥 (*rsa.PrivateKey 或 *ecdsa.PrivateKey)
VerificationKeyany—非对称算法公钥(可选,默认使用 SigningKey)
SigningMethodSigningMethodHS256签名算法
AccessTokenTTLtime.Duration15m访问令牌有效期
RefreshTokenTTLtime.Duration168h刷新令牌有效期
Issuerstring"jwt-service"签发者
ExpectedAudiencestring—期望的受众(可选)
RequireExpirationboolfalse为 true 时拒绝缺少 exp 声明的令牌(返回 ErrExpirationRequired)
RejectRefreshAsAccessboolfalse(v1.2.3 新增)为 true 时 Parse / ParseInto 拒绝 token_type=refresh 的令牌被用作访问令牌(返回 ErrTokenTypeMismatch);Refresh / RefreshInto 不受影响
RotateRefreshTokensboolfalse(v1.2.3 新增)为 true 时 Refresh / RefreshInto 在签发新令牌前先按 jti 吊销传入的刷新令牌,实现一次性使用(fail-closed:吊销失败返回 ErrRefreshRotationFailed,缺 jti 返回 ErrTokenMissingID)。详见令牌刷新与轮换
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 有效性AccessTokenTTL 和 RefreshTokenTTL 必须为正数
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—自定义存储后端(设置后其他字段被忽略)