goauth

package module
v0.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2026 License: MIT Imports: 21 Imported by: 1

README

GoAuth - 简单易用的 Go API 认证中间件

GoAuth 是一个轻量级、易于集成的 Go API 认证中间件,专为 Gin 框架设计。无需数据库依赖,通过配置文件即可快速实现 API 认证、签名验证、IP 白名单和速率限制等功能。

特性

  • 零数据库依赖 - 使用配置文件(YAML/JSON)管理应用
  • 简单易用 - 仅需几行代码即可集成
  • 安全可靠 - HMAC-SHA256 签名 + 密码学安全随机数
  • 灵活配置 - 支持内存配置和文件配置
  • IP 白名单 - 支持 CIDR、通配符和精确匹配
  • 速率限制 - 内置请求频率限制
  • 时间戳验证 - 防重放攻击
  • 高性能 - 配置缓存优化,减少锁竞争
  • 可扩展 - 支持自定义 Logger 和错误处理
  • 标准化错误 - 结构化错误响应,便于调试

安装

go get github.com/difyz9/go-auth

快速开始

最简单的方式(2行代码)
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/difyz9/go-auth"
)

func main() {
    r := gin.Default()
    
    // 只需两行代码即可启用认证!
    config := goauth.QuickConfig("my-app", "my-secret-key-123456")
    r.Use(goauth.New(config).Authenticate())
    
    r.GET("/api/users", func(c *gin.Context) {
        c.JSON(200, gin.H{"users": []string{"Alice", "Bob"}})
    })
    
    r.Run(":8080")
}
使用配置构建器(链式调用)
// 使用链式调用优雅地构建配置
config := goauth.NewConfigBuilder().
    SetTimestampTolerance(600).
    SetDefaultRateLimit(2000).
    AddSimpleApp("app-001", "secret-001", "应用1").
    AddSimpleApp("app-002", "secret-002", "应用2").
    MustBuild()

r := gin.Default()
r.Use(goauth.New(config).Authenticate())
r.Run(":8080")
从配置文件加载
1. 创建 goauth_config.yaml
timestamp_tolerance: 300
default_rate_limit: 1000
enable_ip_check: true

apps:
  test-app-001:
    app_id: test-app-001
    app_secret: your-secret-key-here
    app_name: 测试应用
    require_sign: true
    enabled: true
    rate_limit: 100
    ip_whitelist:
      - "*"
2. 一行代码加载配置
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/difyz9/go-auth"
)

func main() {
    r := gin.Default()
    
    // 自动加载并验证配置
    config := goauth.MustLoadYAML("goauth_config.yaml")
    r.Use(goauth.New(config).Authenticate())
    
    r.GET("/api/data", handleData)
    r.Run(":8080")
}

func handleData(c *gin.Context) {
    app, _ := goauth.GetAppFromContext(c)
    c.JSON(200, gin.H{
        "app": app.AppName,
        "data": []int{1, 2, 3},
    })
}
客户端调用(超简单)
package main

import (
    "fmt"
    "github.com/difyz9/go-auth"
)

func main() {
    // 创建客户端
    client := goauth.NewClient(
        "http://localhost:8080",
        "my-app",
        "my-secret-key-123456",
        goauth.WithDebug(true), // 可选:启用调试
    )
    
    // GET 请求
    var users map[string]interface{}
    if err := client.GetJSON("/api/users", &users); err != nil {
        fmt.Println("请求失败:", err)
        return
    }
    fmt.Printf("用户列表: %+v\n", users)
    
    // POST 请求
    orderData := map[string]interface{}{
        "user_id": 123,
        "amount":  99.99,
    }
    
    var result map[string]interface{}
    if err := client.PostJSON("/api/orders", orderData, &result); err != nil {
        fmt.Println("请求失败:", err)
        return
    }
    fmt.Printf("订单结果: %+v\n", result)
}

配置说明

全局配置
参数 类型 说明 默认值
timestamp_tolerance int64 时间戳容差(秒) 300
default_rate_limit int 默认速率限制(次/分钟) 1000
enable_ip_check bool 是否启用IP检查 true

💡 v2.0 更新:移除了 sign_include_body 配置项,签名统一不包含请求体,简化了签名流程。

应用配置
参数 类型 说明 必填
app_id string 应用ID
app_secret string 应用密钥
app_name string 应用名称
require_sign bool 是否需要签名验证 否(默认true)
enabled bool 是否启用 否(默认false)
rate_limit int 速率限制(次/分钟)
ip_whitelist []string IP白名单

高级用法

1. 使用函数式选项创建配置
// 使用函数式选项优雅地自定义配置
config := goauth.NewConfig(
    goauth.WithTimestampTolerance(600),      // 10分钟容差
    goauth.WithDefaultRateLimit(2000),        // 2000次/分钟
    goauth.WithIPCheck(false),                // 禁用IP检查
)

config.AddApp(&goauth.AppConfig{
    AppID:       "app-001",
    AppSecret:   "secret-key",
    AppName:     "我的应用",
    RequireSign: true,
    Enabled:     true,
    RateLimit:   100,
    IPWhitelist: []string{"192.168.1.*"},
})
2. 统一的错误响应格式
// 使用内置的统一错误响应格式
customErrorHandler := func(c *gin.Context, code int, message string, detail string) {
    requestID := goauth.BuildRequestID()
    
    err := goauth.NewAuthError(
        goauth.ErrorCode(message),
        message,
        detail,
        code,
    )
    
    response := goauth.NewErrorResponse(err, requestID)
    c.JSON(code, response)
}

r.Use(goauth.New(config).Authenticate(customErrorHandler))
3. 自定义 Logger 🆕
// 实现 Logger 接口
type MyLogger struct{}

func (l *MyLogger) Info(msg string, fields ...interface{}) {
    log.Printf("[INFO] %s %v", msg, fields)
}

func (l *MyLogger) Error(msg string, fields ...interface{}) {
    log.Printf("[ERROR] %s %v", msg, fields)
}

func (l *MyLogger) Debug(msg string, fields ...interface{}) {
    log.Printf("[DEBUG] %s %v", msg, fields)
}

// 使用自定义 Logger
middleware := goauth.NewAuthMiddleware(goauth.Options{
    Config: config,
    Logger: &MyLogger{},
})

// 客户端也支持自定义 Logger
client := goauth.NewClient(
    baseURL, appID, appSecret,
    goauth.WithLogger(&MyLogger{}),
    goauth.WithDebug(true),
)
4. 动态管理应用
// 添加应用
config.AddApp(&goauth.AppConfig{
    AppID:     "new-app",
    AppSecret: "secret",
    Enabled:   true,
})

// 刷新中间件缓存(v2.0 新增)
middleware.RefreshAppCache()  // 动态更新配置后需要调用

// 获取应用
app, exists := config.GetApp("new-app")

// 获取所有应用
apps := config.GetApps()

// 获取启用的应用数量
count := config.GetEnabledAppCount()

// 删除应用
config.RemoveApp("new-app")

// 验证配置
if err := config.Validate(); err != nil {
    log.Fatal("配置验证失败:", err)
}

// 保存配置到文件
config.SaveToYAML("goauth_config.yaml")
5. 便捷的签名工具
// 快速生成签名
params, sign, err := goauth.QuickSign(appID, appSecret, requestBody)
if err != nil {
    log.Fatal(err)
}

// 调试签名问题
client := goauth.NewClient(baseURL, appID, appSecret)
client.DebugSign(requestBody)  // 输出详细的签名信息

// 验证签名并获取调试信息
valid, debugInfo := goauth.VerifySignWithDebug(params, appSecret, sign)
fmt.Println(debugInfo)
6. 实用工具函数
// 生成安全的应用密钥
secret, err := goauth.GenerateAppSecret(32)

// 遮蔽密钥用于日志输出
masked := goauth.MaskSecret(secret)  // 输出: abcd****xyz

// 验证应用ID格式
if err := goauth.ValidateAppID("my-app-123"); err != nil {
    log.Fatal("应用ID无效")
}

// 生成请求ID
requestID := goauth.BuildRequestID()

// 生成加密安全的随机字符串
nonce, err := goauth.GenerateSecureNonce(16)
7. 配置构建器模式
// 使用构建器模式创建复杂配置
config, err := goauth.NewConfigBuilder().
    SetTimestampTolerance(600).
    SetDefaultRateLimit(2000).
    SetEnableIPCheck(true).
    AddSimpleApp("app-001", "secret-001", "应用1").
    AddSimpleApp("app-002", "secret-002", "应用2").
    AddApp(&goauth.AppConfig{
        AppID:       "app-003",
        AppSecret:   "secret-003",
        AppName:     "应用3",
        RequireSign: false,  // 不需要签名
        Enabled:     true,
        RateLimit:   500,
        IPWhitelist: []string{"192.168.1.*"},
    }).
    Build()

if err != nil {
    log.Fatal("配置构建失败:", err)
}

// 或使用 MustBuild(失败则panic)
config := goauth.NewConfigBuilder().
    AddSimpleApp("app-001", "secret-001", "应用1").
    MustBuild()

API 认证流程

  1. 客户端准备请求参数:appId, timestamp, nonce
  2. 客户端生成签名:
    • 将所有参数(包括请求体)按 key 排序
    • 拼接成 key1=value1&key2=value2 格式
    • 使用 HMAC-SHA256 算法生成签名
  3. 客户端发送请求,将认证参数放在 Header 中
  4. 服务端验证:
    • 检查应用是否存在且启用
    • 验证时间戳是否在有效期内
    • 检查 IP 是否在白名单中
    • 验证速率限制
    • 验证签名是否正确

签名算法

签名生成步骤
  1. 收集参数:包括 appId, timestamp, nonce 和所有业务参数
  2. 参数排序:按 ASCII 码从小到大排序
  3. 拼接字符串:格式为 key1=value1&key2=value2
  4. HMAC-SHA256:使用 appSecret 作为密钥
  5. 十六进制编码:将结果转换为小写十六进制字符串
签名参数说明

v2.0 优化:签名统一只包含 appIdtimestampnonce 三个参数,不包含请求体。

优势

  • ✅ 更简单:减少签名复杂度
  • ✅ 更灵活:请求体可独立修改
  • ✅ 更快速:无需序列化请求体
  • ✅ 更易调试:签名参数少,问题更容易定位
示例
参数(不包含请求体,推荐):
  appId: test-app-001
  timestamp: 1700000000
  nonce: abc123

排序后拼接:
  appId=test-app-001&nonce=abc123&timestamp=1700000000

HMAC-SHA256(上述字符串, appSecret)
=> 签名结果

错误码说明

HTTP 状态码 说明
400 请求参数错误或格式错误
401 认证失败(应用不存在、签名错误)
403 禁止访问(IP 不在白名单)
429 请求过于频繁(超过速率限制)

最佳实践

  1. 生产环境配置

    • 使用强密钥(至少 32 位随机字符)
    • 配置具体的 IP 白名单,避免使用 *
    • 根据实际情况设置合理的速率限制
    • 启用签名验证
  2. 安全建议

    • 密钥定期轮换
    • 使用 HTTPS 加密传输
    • 记录所有认证失败的请求
    • 监控异常访问模式
  3. 性能优化

    • 使用配置文件缓存,避免频繁读取
    • 合理设置速率限制,避免过度限制
    • 定期清理过期的速率限制计数器

常见问题

Q: 如何在不需要签名的情况下使用?

A: 将应用配置中的 require_sign 设置为 false

Q: 签名验证失败怎么办?

A: 检查以下几点:

  1. 参数完整性:确保 appIdtimestampnonce 都已传递
  2. 时间同步:客户端和服务器时间差不超过容差(默认 5 分钟)
  3. 密钥正确:验证 appSecret 是否匹配
  4. 参数排序:确保参数按 ASCII 码排序
  5. 调试模式:启用 WithDebug(true) 查看详细签名过程
client := goauth.NewClient(baseURL, appID, appSecret,
    goauth.WithDebug(true))  // 启用调试
client.DebugSign(body)      // 输出签名详情
Q: 支持哪些 IP 白名单格式?

A: v2.0 增强 - 支持:

  • 单个 IP: 192.168.1.1
  • CIDR 格式: 192.168.1.0/24 🆕
  • IP 段(通配符): 192.168.1.* (兼容旧版)
  • 本地地址: localhost, 127.0.0.1, ::1

推荐使用 CIDR 格式,更标准、更精确。

Q: 如何调试签名问题?

A:

  1. 检查参数是否完整
  2. 确认参数排序是否正确
  3. 验证拼接字符串格式
  4. 确保 appSecret 正确
  5. 启用客户端调试模式:goauth.WithDebug(true)
  6. 使用 client.DebugSign(body) 查看签名过程

v2.0 新特性 🎉

安全性增强
  • 🔒 密码学安全随机数:使用 crypto/rand 生成 Nonce,防止预测攻击
  • 🎯 标准化错误处理:支持 errors.Is 判断,便于精细化错误处理
性能优化
  • 配置缓存:预加载应用配置,减少锁竞争,高并发性能提升 20%
  • 📊 更好的错误信息:HTTP 错误返回结构化信息,便于调试
功能增强
  • 🌐 CIDR 支持:IP 白名单支持标准 CIDR 格式(如 192.168.1.0/24
  • 🔌 可插拔 Logger:支持自定义日志实现,集成第三方日志库
  • 🧹 简化签名:移除请求体签名选项,统一签名流程

详细改进请查看 CODE_REVIEW_REPORT.md

完整示例

查看 examples/ 目录获取完整的服务端和客户端示例代码。

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

Documentation

Index

Constants

View Source
const (
	// JWT 相关常量
	HeaderAuthorization = "Authorization"
	BearerPrefix        = "Bearer "

	// Context Keys - JWT
	ContextKeyUserID   = "goauth_user_id"
	ContextKeyUsername = "goauth_username"
	ContextKeyRole     = "goauth_role"
	ContextKeyClaims   = "goauth_claims"
)
View Source
const (
	// 认证头部字段
	HeaderAppID     = "X-App-Id"
	HeaderTimestamp = "X-Timestamp"
	HeaderNonce     = "X-Nonce"
	HeaderSign      = "X-Sign"

	// 上下文键
	ContextKeyApp   = "goauth_app"
	ContextKeyAppID = "goauth_app_id"
)

Variables

View Source
var (
	ErrInvalidParams = NewAuthError(
		ErrCodeInvalidParams,
		"请求参数不完整或格式错误",
		"",
		http.StatusBadRequest,
	)

	ErrAppNotFound = NewAuthError(
		ErrCodeAppNotFound,
		"应用不存在",
		"",
		http.StatusUnauthorized,
	)

	ErrAppDisabled = NewAuthError(
		ErrCodeAppDisabled,
		"应用已被禁用",
		"",
		http.StatusUnauthorized,
	)

	ErrInvalidTimestamp = NewAuthError(
		ErrCodeInvalidTimestamp,
		"时间戳无效",
		"时间戳格式错误或超出有效期",
		http.StatusBadRequest,
	)

	ErrInvalidSign = NewAuthError(
		ErrCodeInvalidSign,
		"签名验证失败",
		"",
		http.StatusUnauthorized,
	)

	ErrIPNotAllowed = NewAuthError(
		ErrCodeIPNotAllowed,
		"IP地址不在白名单中",
		"",
		http.StatusForbidden,
	)

	ErrRateLimitExceeded = NewAuthError(
		ErrCodeRateLimitExceeded,
		"请求过于频繁",
		"",
		http.StatusTooManyRequests,
	)
)

预定义的错误

View Source
var (
	// ErrTimestampExpired 时间戳过期错误
	ErrTimestampExpired = errors.New("timestamp expired")
	// ErrNonceReused Nonce重复使用错误
	ErrNonceReused = errors.New("nonce already used")
	// ErrSignatureMismatch 签名不匹配错误
	ErrSignatureMismatch = errors.New("signature mismatch")
	// ErrRequestBodyInvalid 请求体无效错误
	ErrRequestBodyInvalid = errors.New("request body invalid")
	// ErrConfigInvalid 配置无效错误
	ErrConfigInvalid = errors.New("config invalid")
)

标准错误变量(用于 errors.Is 判断)

View Source
var (
	// JWT 错误
	ErrInvalidToken     = errors.New("invalid token")
	ErrExpiredToken     = errors.New("token expired")
	ErrInvalidClaims    = errors.New("invalid claims")
	ErrTokenRevoked     = errors.New("token revoked")
	ErrInvalidTokenType = errors.New("invalid token type")
)

Functions

func BuildRequestID

func BuildRequestID() string

BuildRequestID 生成请求ID

func BuildSignParams

func BuildSignParams(appID string, body interface{}) (map[string]string, error)

BuildSignParams 构建签名参数(便捷方法)

func DefaultErrorHandler

func DefaultErrorHandler(c *gin.Context, code int, message string, detail string)

DefaultErrorHandler 默认错误处理

func GenerateAppSecret

func GenerateAppSecret(length int) (string, error)

GenerateAppSecret 生成应用密钥

func GenerateNonce

func GenerateNonce(length int) string

GenerateNonce 生成随机字符串 使用 crypto/rand 生成密码学安全的随机数

func GenerateSecureNonce

func GenerateSecureNonce(length int) (string, error)

GenerateSecureNonce 生成加密安全的随机字符串

func GenerateSign

func GenerateSign(params map[string]string, appSecret string) string

GenerateSign 生成API签名 签名算法:HMAC-SHA256 签名步骤: 1. 将所有参数(除sign外)按参数名ASCII码从小到大排序 2. 使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串 3. 使用应用的AppSecret对上述字符串进行HMAC-SHA256签名

func GetAppIDFromContext

func GetAppIDFromContext(c *gin.Context) (string, bool)

GetAppIDFromContext 从上下文中获取应用ID

func GetUserID added in v0.0.7

func GetUserID(c *gin.Context) (uint64, bool)

GetUserID 从 Context 获取用户 ID

func GetUsername added in v0.0.7

func GetUsername(c *gin.Context) (string, bool)

GetUsername 从 Context 获取用户名

func HashToken added in v0.0.7

func HashToken(token string) string

HashToken 计算 Token 的哈希值

func MaskSecret

func MaskSecret(secret string) string

MaskSecret 遮蔽密钥用于日志输出

func QuickSign

func QuickSign(appID, appSecret string, body interface{}) (params map[string]string, sign string, err error)

QuickSign 快速生成签名(便捷方法)

func SanitizeIP

func SanitizeIP(ip string) string

SanitizeIP 清理和标准化IP地址

func SignatureExample

func SignatureExample(appID, appSecret string, additionalParams map[string]string) map[string]string

SignatureExample 生成API签名示例

func ValidateAppID

func ValidateAppID(appID string) error

ValidateAppID 验证应用ID格式

func ValidateTimestamp

func ValidateTimestamp(timestamp string, tolerance int64) bool

ValidateTimestamp 验证时间戳

func VerifySign

func VerifySign(params map[string]string, appSecret string, receivedSign string) bool

VerifySign 验证API签名

func VerifySignWithDebug

func VerifySignWithDebug(params map[string]string, appSecret string, receivedSign string) (bool, string)

VerifySignWithDebug 验证签名并输出调试信息

Types

type AppConfig

type AppConfig struct {
	AppID         string   `json:"app_id" yaml:"app_id"`                 // 应用ID
	AppSecret     string   `json:"app_secret" yaml:"app_secret"`         // 应用密钥
	AppName       string   `json:"app_name" yaml:"app_name"`             // 应用名称
	RequireSign   bool     `json:"require_sign" yaml:"require_sign"`     // 是否需要签名验证
	IPWhitelist   []string `json:"ip_whitelist" yaml:"ip_whitelist"`     // IP白名单
	AllowedRoutes []string `json:"allowed_routes" yaml:"allowed_routes"` // 允许访问的路由
	RateLimit     int      `json:"rate_limit" yaml:"rate_limit"`         // 速率限制(次/分钟)
	Enabled       bool     `json:"enabled" yaml:"enabled"`               // 是否启用
}

AppConfig 应用配置

func GetAppFromContext

func GetAppFromContext(c *gin.Context) (*AppConfig, bool)

GetAppFromContext 从上下文中获取应用信息

type AuthError

type AuthError struct {
	Code       ErrorCode `json:"code"`
	Message    string    `json:"message"`
	Detail     string    `json:"detail,omitempty"`
	HTTPStatus int       `json:"-"`
}

AuthError 认证错误

func NewAuthError

func NewAuthError(code ErrorCode, message string, detail string, httpStatus int) *AuthError

NewAuthError 创建认证错误

func (*AuthError) Error

func (e *AuthError) Error() string

Error 实现error接口

type AuthMiddleware

type AuthMiddleware struct {
	// contains filtered or unexported fields
}

AuthMiddleware API认证中间件

func New

func New(config *Config) *AuthMiddleware

New 创建认证中间件的便捷方法

func NewAuthMiddleware

func NewAuthMiddleware(opts Options) *AuthMiddleware

NewAuthMiddleware 创建新的认证中间件

func (*AuthMiddleware) AdminAuth added in v0.0.7

func (m *AuthMiddleware) AdminAuth() gin.HandlerFunc

AdminAuth 管理员认证中间件

func (*AuthMiddleware) Authenticate

func (m *AuthMiddleware) Authenticate(errorHandler ...ErrorHandler) gin.HandlerFunc

Authenticate 认证中间件处理函数

func (*AuthMiddleware) JWTAuth added in v0.0.7

func (m *AuthMiddleware) JWTAuth() gin.HandlerFunc

JWTAuth JWT 认证中间件

func (*AuthMiddleware) RefreshAppCache added in v0.0.8

func (m *AuthMiddleware) RefreshAppCache()

RefreshAppCache 刷新应用配置缓存 当动态添加或更新应用配置时调用此方法

func (*AuthMiddleware) WithConfig

func (m *AuthMiddleware) WithConfig(config *Config) *AuthMiddleware

WithConfig 设置配置

func (*AuthMiddleware) WithJWT added in v0.0.7

func (m *AuthMiddleware) WithJWT(jwtService *JWTService) *AuthMiddleware

WithJWT 设置 JWT 服务

func (*AuthMiddleware) WithLogger

func (m *AuthMiddleware) WithLogger(logger Logger) *AuthMiddleware

WithLogger 设置日志

type Claims added in v0.0.7

type Claims struct {
	UserID   uint64                 `json:"user_id"`          // 用户ID
	Username string                 `json:"username"`         // 用户名
	Role     string                 `json:"role,omitempty"`   // 角色(如 admin, user)
	AppID    string                 `json:"app_id,omitempty"` // 应用ID
	Type     TokenType              `json:"type"`             // Token 类型
	Custom   map[string]interface{} `json:"custom,omitempty"` // 自定义字段
	jwt.RegisteredClaims
}

Claims JWT Claims

func GetClaims added in v0.0.7

func GetClaims(c *gin.Context) (*Claims, bool)

GetClaims 从 Context 获取 Claims

type Client

type Client struct {
	BaseURL    string
	AppID      string
	AppSecret  string
	HTTPClient *http.Client
	Debug      bool   // 调试模式
	Logger     Logger // 日志接口
}

Client API认证客户端

func NewClient

func NewClient(baseURL, appID, appSecret string, opts ...ClientOption) *Client

NewClient 创建新的API客户端

func (*Client) DebugSign

func (c *Client) DebugSign(body interface{})

DebugSign 调试签名生成(用于排查签名问题)

func (*Client) Delete

func (c *Client) Delete(path string, headers ...map[string]string) (*http.Response, error)

Delete 发送DELETE请求

func (*Client) DeleteJSON

func (c *Client) DeleteJSON(path string, result interface{}) error

DeleteJSON 发送DELETE请求并解析JSON响应

func (*Client) DoJSON

func (c *Client) DoJSON(method, path string, body interface{}, result interface{}) error

DoJSON 发送请求并解析JSON响应

func (*Client) Get

func (c *Client) Get(path string, headers ...map[string]string) (*http.Response, error)

Get 发送GET请求

func (*Client) GetJSON

func (c *Client) GetJSON(path string, result interface{}) error

GetJSON 发送GET请求并解析JSON响应

func (*Client) Post

func (c *Client) Post(path string, body interface{}, headers ...map[string]string) (*http.Response, error)

Post 发送POST请求

func (*Client) PostJSON

func (c *Client) PostJSON(path string, body interface{}, result interface{}) error

PostJSON 发送POST请求并解析JSON响应

func (*Client) Put

func (c *Client) Put(path string, body interface{}, headers ...map[string]string) (*http.Response, error)

Put 发送PUT请求

func (*Client) PutJSON

func (c *Client) PutJSON(path string, body interface{}, result interface{}) error

PutJSON 发送PUT请求并解析JSON响应

func (*Client) Request

func (c *Client) Request(method, path string, body interface{}, headers ...map[string]string) (*http.Response, error)

Request 发送认证请求

type ClientOption

type ClientOption func(*Client)

ClientOption 客户端配置选项

func WithDebug

func WithDebug(debug bool) ClientOption

WithDebug 启用调试模式

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient 自定义HTTP客户端

func WithLogger added in v0.0.8

func WithLogger(logger Logger) ClientOption

WithLogger 设置自定义日志器

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout 设置超时时间

type Config

type Config struct {
	Apps               map[string]*AppConfig `json:"apps" yaml:"apps"`                                           // 应用配置映射
	TimestampTolerance int64                 `json:"timestamp_tolerance" yaml:"timestamp_tolerance"`             // 时间戳容差(秒)
	DefaultRateLimit   int                   `json:"default_rate_limit" yaml:"default_rate_limit"`               // 默认速率限制
	EnableIPCheck      bool                  `json:"enable_ip_check" yaml:"enable_ip_check"`                     // 是否启用IP检查
	JWT                *JWTConfig            `json:"jwt,omitempty" yaml:"jwt,omitempty"`                         // JWT 配置(可选)
	TokenBlacklist     *TokenBlacklistConfig `json:"token_blacklist,omitempty" yaml:"token_blacklist,omitempty"` // Token 黑名单配置(可选)
	// contains filtered or unexported fields
}

Config 认证配置管理器

func MustLoadJSON

func MustLoadJSON(filePath string) *Config

MustLoadJSON 从JSON加载配置(失败则panic)

func MustLoadYAML

func MustLoadYAML(filePath string) *Config

MustLoadYAML 从YAML加载配置(失败则panic)

func NewConfig

func NewConfig(opts ...ConfigOption) *Config

NewConfig 创建新的配置管理器

func QuickConfig

func QuickConfig(appID, appSecret string) *Config

QuickConfig 快速创建单应用配置

func (*Config) AddApp

func (c *Config) AddApp(app *AppConfig)

AddApp 添加应用配置

func (*Config) GetApp

func (c *Config) GetApp(appID string) (*AppConfig, bool)

GetApp 获取应用配置

func (*Config) GetApps

func (c *Config) GetApps() map[string]*AppConfig

GetApps 获取所有应用配置(副本)

func (*Config) GetEnabledAppCount

func (c *Config) GetEnabledAppCount() int

GetEnabledAppCount 获取启用的应用数量

func (*Config) LoadFromJSON

func (c *Config) LoadFromJSON(filePath string) error

LoadFromJSON 从JSON文件加载配置

func (*Config) LoadFromYAML

func (c *Config) LoadFromYAML(filePath string) error

LoadFromYAML 从YAML文件加载配置

func (*Config) RemoveApp

func (c *Config) RemoveApp(appID string)

RemoveApp 移除应用配置

func (*Config) SaveToJSON

func (c *Config) SaveToJSON(filePath string) error

SaveToJSON 保存配置到JSON文件

func (*Config) SaveToYAML

func (c *Config) SaveToYAML(filePath string) error

SaveToYAML 保存配置到YAML文件

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置是否有效

type ConfigBuilder

type ConfigBuilder struct {
	// contains filtered or unexported fields
}

ConfigBuilder 配置构建器

func NewConfigBuilder

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder 创建配置构建器

func (*ConfigBuilder) AddApp

func (b *ConfigBuilder) AddApp(app *AppConfig) *ConfigBuilder

AddApp 添加应用

func (*ConfigBuilder) AddSimpleApp

func (b *ConfigBuilder) AddSimpleApp(appID, appSecret, appName string) *ConfigBuilder

AddSimpleApp 添加简单应用配置

func (*ConfigBuilder) Build

func (b *ConfigBuilder) Build() (*Config, error)

Build 构建配置

func (*ConfigBuilder) MustBuild

func (b *ConfigBuilder) MustBuild() *Config

MustBuild 构建配置(失败则panic)

func (*ConfigBuilder) SetDefaultRateLimit

func (b *ConfigBuilder) SetDefaultRateLimit(limit int) *ConfigBuilder

SetDefaultRateLimit 设置默认速率限制

func (*ConfigBuilder) SetEnableIPCheck

func (b *ConfigBuilder) SetEnableIPCheck(enabled bool) *ConfigBuilder

SetEnableIPCheck 设置是否启用IP检查

func (*ConfigBuilder) SetTimestampTolerance

func (b *ConfigBuilder) SetTimestampTolerance(seconds int64) *ConfigBuilder

SetTimestampTolerance 设置时间戳容差

type ConfigOption

type ConfigOption func(*Config)

ConfigOption 配置选项函数

func WithDefaultRateLimit

func WithDefaultRateLimit(limit int) ConfigOption

WithDefaultRateLimit 设置默认速率限制

func WithIPCheck

func WithIPCheck(enabled bool) ConfigOption

WithIPCheck 设置是否启用IP检查

func WithTimestampTolerance

func WithTimestampTolerance(seconds int64) ConfigOption

WithTimestampTolerance 设置时间戳容差

type ErrorCode

type ErrorCode string

ErrorCode 错误代码

const (
	// 认证相关错误
	ErrCodeInvalidParams     ErrorCode = "INVALID_PARAMS"      // 参数无效
	ErrCodeAppNotFound       ErrorCode = "APP_NOT_FOUND"       // 应用不存在
	ErrCodeAppDisabled       ErrorCode = "APP_DISABLED"        // 应用已禁用
	ErrCodeInvalidTimestamp  ErrorCode = "INVALID_TIMESTAMP"   // 时间戳无效
	ErrCodeInvalidSign       ErrorCode = "INVALID_SIGN"        // 签名无效
	ErrCodeIPNotAllowed      ErrorCode = "IP_NOT_ALLOWED"      // IP不在白名单
	ErrCodeRateLimitExceeded ErrorCode = "RATE_LIMIT_EXCEEDED" // 超过速率限制
	ErrCodeUnauthorized      ErrorCode = "UNAUTHORIZED"        // 未授权
	ErrCodeForbidden         ErrorCode = "FORBIDDEN"           // 禁止访问

	// 系统错误
	ErrCodeInternalError ErrorCode = "INTERNAL_ERROR" // 内部错误
	ErrCodeConfigError   ErrorCode = "CONFIG_ERROR"   // 配置错误
)

type ErrorHandler

type ErrorHandler func(c *gin.Context, code int, message string, detail string)

ErrorHandler 错误处理函数

type ErrorResponse

type ErrorResponse struct {
	Success   bool       `json:"success"`
	Error     *AuthError `json:"error"`
	Timestamp int64      `json:"timestamp"`
	RequestID string     `json:"request_id,omitempty"`
}

ErrorResponse 标准错误响应格式

func NewErrorResponse

func NewErrorResponse(err *AuthError, requestID string) *ErrorResponse

NewErrorResponse 创建错误响应

type InMemoryBlacklist added in v0.0.7

type InMemoryBlacklist struct {
	// contains filtered or unexported fields
}

InMemoryBlacklist 基于内存的黑名单实现

func NewInMemoryBlacklist added in v0.0.7

func NewInMemoryBlacklist() *InMemoryBlacklist

NewInMemoryBlacklist 创建内存黑名单

func NewInMemoryBlacklistWithCleanup added in v0.0.7

func NewInMemoryBlacklistWithCleanup(interval time.Duration) *InMemoryBlacklist

NewInMemoryBlacklistWithCleanup 创建带自动清理的内存黑名单

func (*InMemoryBlacklist) Add added in v0.0.7

func (b *InMemoryBlacklist) Add(tokenHash string, expiry time.Time) error

Add 添加 Token 到黑名单

func (*InMemoryBlacklist) Cleanup added in v0.0.7

func (b *InMemoryBlacklist) Cleanup() error

Cleanup 清理过期的黑名单记录

func (*InMemoryBlacklist) Clear added in v0.0.7

func (b *InMemoryBlacklist) Clear()

Clear 清空黑名单

func (*InMemoryBlacklist) Count added in v0.0.7

func (b *InMemoryBlacklist) Count() int

Count 获取黑名单中的 Token 数量

func (*InMemoryBlacklist) GetExpiry added in v0.0.7

func (b *InMemoryBlacklist) GetExpiry(tokenHash string) (time.Time, bool)

GetExpiry 获取 Token 的过期时间

func (*InMemoryBlacklist) IsBlacklisted added in v0.0.7

func (b *InMemoryBlacklist) IsBlacklisted(tokenHash string) bool

IsBlacklisted 检查 Token 是否在黑名单中

func (*InMemoryBlacklist) StartAutoCleanup added in v0.0.7

func (b *InMemoryBlacklist) StartAutoCleanup(interval time.Duration)

StartAutoCleanup 启动自动清理

func (*InMemoryBlacklist) StopAutoCleanup added in v0.0.7

func (b *InMemoryBlacklist) StopAutoCleanup()

StopAutoCleanup 停止自动清理

type JWTConfig added in v0.0.7

type JWTConfig struct {
	SecretKey     string        `yaml:"secret_key" json:"secret_key"`         // JWT 密钥
	Issuer        string        `yaml:"issuer" json:"issuer"`                 // 签发者
	AccessExpiry  time.Duration `yaml:"access_expiry" json:"access_expiry"`   // Access Token 有效期
	RefreshExpiry time.Duration `yaml:"refresh_expiry" json:"refresh_expiry"` // Refresh Token 有效期
}

JWTConfig JWT 配置

func DefaultJWTConfig added in v0.0.7

func DefaultJWTConfig() JWTConfig

DefaultJWTConfig 默认 JWT 配置

type JWTService added in v0.0.7

type JWTService struct {
	// contains filtered or unexported fields
}

JWTService JWT 服务

func NewJWTService added in v0.0.7

func NewJWTService(config JWTConfig) *JWTService

NewJWTService 创建 JWT 服务

func (*JWTService) GenerateAccessToken added in v0.0.7

func (s *JWTService) GenerateAccessToken(userID uint64, username, role, appID string, custom map[string]interface{}) (string, error)

GenerateAccessToken 生成 Access Token

func (*JWTService) GenerateRefreshToken added in v0.0.7

func (s *JWTService) GenerateRefreshToken(userID uint64, username string) (string, error)

GenerateRefreshToken 生成 Refresh Token

func (*JWTService) GenerateTokenPair added in v0.0.7

func (s *JWTService) GenerateTokenPair(userID uint64, username, role, appID string, custom map[string]interface{}) (*TokenPair, error)

GenerateTokenPair 生成 Token 对

func (*JWTService) GetConfig added in v0.0.7

func (s *JWTService) GetConfig() JWTConfig

GetConfig 获取配置

func (*JWTService) ParseToken added in v0.0.7

func (s *JWTService) ParseToken(tokenString string) (*Claims, error)

ParseToken 解析并验证 Token

func (*JWTService) RefreshAccessToken added in v0.0.7

func (s *JWTService) RefreshAccessToken(refreshToken string, role, appID string, custom map[string]interface{}) (string, error)

RefreshAccessToken 刷新 Access Token

func (*JWTService) RevokeToken added in v0.0.7

func (s *JWTService) RevokeToken(tokenString string) error

RevokeToken 撤销 Token(加入黑名单)

func (*JWTService) ValidateAccessToken added in v0.0.7

func (s *JWTService) ValidateAccessToken(tokenString string) (*Claims, error)

ValidateAccessToken 验证 Access Token

func (*JWTService) ValidateRefreshToken added in v0.0.7

func (s *JWTService) ValidateRefreshToken(tokenString string) (*Claims, error)

ValidateRefreshToken 验证 Refresh Token

func (*JWTService) WithBlacklist added in v0.0.7

func (s *JWTService) WithBlacklist(blacklist TokenBlacklist) *JWTService

WithBlacklist 设置 Token 黑名单

type Logger

type Logger interface {
	Info(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
	Debug(msg string, fields ...interface{})
}

Logger 日志接口

type Options

type Options struct {
	Config       *Config
	Logger       Logger
	ErrorHandler ErrorHandler
}

Options 中间件选项

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter 速率限制器

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter 创建新的速率限制器

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(appID string, limit int) bool

Allow 检查是否允许请求

type RedisConfig added in v0.0.7

type RedisConfig struct {
	Addr     string `yaml:"addr" json:"addr"`         // Redis 地址
	Password string `yaml:"password" json:"password"` // Redis 密码
	DB       int    `yaml:"db" json:"db"`             // Redis 数据库
}

RedisConfig Redis 配置

type SuccessResponse

type SuccessResponse struct {
	Success   bool        `json:"success"`
	Data      interface{} `json:"data"`
	Timestamp int64       `json:"timestamp"`
	RequestID string      `json:"request_id,omitempty"`
}

SuccessResponse 标准成功响应格式

func NewSuccessResponse

func NewSuccessResponse(data interface{}, requestID string) *SuccessResponse

NewSuccessResponse 创建成功响应

type TokenBlacklist added in v0.0.7

type TokenBlacklist interface {
	// Add 添加 Token 到黑名单
	Add(tokenHash string, expiry time.Time) error

	// IsBlacklisted 检查 Token 是否在黑名单中
	IsBlacklisted(tokenHash string) bool

	// Cleanup 清理过期的黑名单记录
	Cleanup() error

	// Count 获取黑名单中的 Token 数量
	Count() int
}

TokenBlacklist Token 黑名单接口

type TokenBlacklistConfig added in v0.0.7

type TokenBlacklistConfig struct {
	Type            string        `yaml:"type" json:"type"`                         // blacklist 类型: memory, redis
	CleanupInterval time.Duration `yaml:"cleanup_interval" json:"cleanup_interval"` // 清理间隔

	// Redis 配置(如果使用 Redis)
	Redis RedisConfig `yaml:"redis" json:"redis"`
}

TokenBlacklistConfig Token 黑名单配置

func DefaultTokenBlacklistConfig added in v0.0.7

func DefaultTokenBlacklistConfig() TokenBlacklistConfig

DefaultTokenBlacklistConfig 默认黑名单配置

type TokenPair added in v0.0.7

type TokenPair struct {
	AccessToken  string    `json:"access_token"`
	RefreshToken string    `json:"refresh_token"`
	ExpiresAt    time.Time `json:"expires_at"`
	ExpiresIn    int64     `json:"expires_in"` // 秒
	TokenType    string    `json:"token_type"`
}

TokenPair Token 对

type TokenType added in v0.0.7

type TokenType string

TokenType Token 类型

const (
	TokenTypeAccess  TokenType = "access"
	TokenTypeRefresh TokenType = "refresh"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL