root 11fc10ba8a feat: 添加API授权中间件
为所有API接口添加授权验证,要求请求头中包含有效的API密钥才能访问。

主要变更:
- 新增授权中间件 (internal/middleware/auth.go)
  - 验证 X-API-Key 请求头
  - 密钥值为 xn001624.
  - 无效密钥返回 401 Unauthorized

- 更新路由配置 (cmd/server/main.go)
  - 使用路由组统一应用授权中间件
  - 保护所有文件和存储桶操作接口
  - Swagger 和 Web UI 保持公开访问

- 新增授权使用文档 (docs/AUTH_GUIDE.md)
  - 多语言使用示例 (cURL, JavaScript, Python)
  - 完整的错误说明和授权范围

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 20:22:04 +08:00

35 lines
694 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
const (
API_KEY_HEADER = "X-API-Key"
API_KEY_VALUE = "xn001624."
)
// AuthMiddleware 验证API密钥的中间件
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取API密钥
apiKey := c.GetHeader(API_KEY_HEADER)
// 验证密钥是否正确
if apiKey != API_KEY_VALUE {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "未授权请在请求头中提供有效的API密钥",
"error": "Missing or invalid API key",
})
c.Abort()
return
}
// 密钥验证通过,继续处理请求
c.Next()
}
}