Documentation
¶
Overview ¶
Package auth 提供基于 JWT 的认证能力。
遵循 Genesis L3 治理层规范,支持:
- Token 生成、验证与刷新
- Gin 中间件集成
- 基于角色的访问控制 (RBAC)
- 多种 Token 提取方式 (Header, Cookie, Query)
基本使用:
authenticator, _ := auth.New(&auth.Config{SecretKey: "..."})
token, _ := authenticator.GenerateToken(ctx, &auth.Claims{
RegisteredClaims: jwt.RegisteredClaims{Subject: "user-123"},
})
Index ¶
Constants ¶
View Source
const ( // MetricTokensValidated Token 验证计数,标签: status, error_type MetricTokensValidated = "auth_tokens_validated_total" // MetricTokensRefreshed Token 刷新计数,标签: status MetricTokensRefreshed = "auth_tokens_refreshed_total" )
View Source
const ClaimsKey = "auth:claims"
Variables ¶
View Source
var ( ErrInvalidToken = xerrors.New("auth: invalid token") ErrExpiredToken = xerrors.New("auth: token expired") ErrMissingToken = xerrors.New("auth: missing token") ErrInvalidClaims = xerrors.New("auth: invalid claims") ErrInvalidSignature = xerrors.New("auth: invalid signature") ErrInvalidConfig = xerrors.New("auth: invalid config") )
Functions ¶
func RequireRoles ¶
func RequireRoles(roles ...string) gin.HandlerFunc
RequireRoles 要求用户拥有其中一个角色的中间件,采用 OR 逻辑 RequireRoles("admin", "editor") 表示用户必须拥有 admin 或 editor 角色之一
Types ¶
type Authenticator ¶
type Authenticator interface {
// GenerateToken 生成 Token
GenerateToken(ctx context.Context, claims *Claims) (string, error)
// ValidateToken 验证 Token,返回 Claims
ValidateToken(ctx context.Context, token string) (*Claims, error)
// RefreshToken 刷新 Token
RefreshToken(ctx context.Context, token string) (string, error)
// GinMiddleware 返回 Gin 认证中间件
GinMiddleware() gin.HandlerFunc
}
Authenticator 认证器接口
type Claims ¶
type Claims struct {
// 标准声明 (包含 Subject, Issuer, ExpiresAt 等)
jwt.RegisteredClaims
// 业务扩展声明
Username string `json:"uname,omitempty"` // 用户名
Roles []string `json:"roles,omitempty"` // 角色列表
Extra map[string]any `json:"extra,omitempty"` // 扩展信息
}
Claims 定义了 JWT 载荷结构。
它内嵌了 jwt.RegisteredClaims 以支持标准声明(如 exp, sub, iss 等), 同时扩展了 Genesis 框架常用的业务字段。
字段说明:
- Username: 用户名 (对应 uname)
- Roles: 角色列表 (对应 roles)
- Extra: 扩展字段 (对应 extra)
type Config ¶
type Config struct {
// JWT 配置
SecretKey string `mapstructure:"secret_key"` // 签名密钥(至少 32 字符)
SigningMethod string `mapstructure:"signing_method"` // 签名方法: HS256(目前只支持)
Issuer string `mapstructure:"issuer"` // 签发者
Audience []string `mapstructure:"audience"` // 接收者
// Token 有效期
AccessTokenTTL time.Duration `mapstructure:"access_token_ttl"` // Access Token TTL,默认 15m
RefreshTokenTTL time.Duration `mapstructure:"refresh_token_ttl"` // Refresh Token TTL,默认 7d
// Token 提取配置(可选,覆盖默认查找顺序)
// 默认顺序: header:Authorization -> query:token -> cookie:jwt
// 可指定单一来源如 "header:Authorization" 或 "query:token"
TokenLookup string `mapstructure:"token_lookup"` // 提取方式,留空使用默认多源查找
TokenHeadName string `mapstructure:"token_head_name"` // Header 前缀,默认 Bearer
}
Config Auth 配置
Click to show internal directories.
Click to hide internal directories.