为所有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>
35 lines
694 B
Go
35 lines
694 B
Go
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()
|
||
}
|
||
}
|