mirror of
https://github.com/xpzouying/xiaohongshu-mcp.git
synced 2026-08-28 09:36:40 +08:00
16ec75c7a3
为 /api/v1/* 与 /mcp 增加可选的静态 Bearer Token 鉴权,默认关闭以保持向后兼容。 - 通过 AUTH_TOKEN 环境变量或 -token 启动参数配置,非空参数优先 - /health 与 CORS OPTIONS 预检保持公开 - scheme 大小写不敏感,仅对 credentials 做常量时间比较 - Token 不出现在日志、错误响应与 -h 帮助输出中 - 补充中英文 README、docs/API.md 与 Docker 文档
61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// authMiddleware 静态 Bearer Token 鉴权中间件,Token 为空时关闭鉴权。
|
|
func authMiddleware(token string) gin.HandlerFunc {
|
|
expectedToken := []byte(token)
|
|
|
|
return func(c *gin.Context) {
|
|
if token == "" {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
scheme, credentials, found := strings.Cut(c.GetHeader("Authorization"), " ")
|
|
credentials = strings.TrimLeft(credentials, " ")
|
|
if !found || !strings.EqualFold(scheme, "Bearer") ||
|
|
subtle.ConstantTimeCompare([]byte(credentials), expectedToken) != 1 {
|
|
c.Header("WWW-Authenticate", "Bearer")
|
|
respondError(c, http.StatusUnauthorized, "UNAUTHORIZED", "未授权", nil)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// corsMiddleware CORS 中间件
|
|
func corsMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Header("Access-Control-Allow-Origin", "*")
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// errorHandlingMiddleware 错误处理中间件
|
|
func errorHandlingMiddleware() gin.HandlerFunc {
|
|
return gin.CustomRecovery(func(c *gin.Context, recovered any) {
|
|
logrus.Errorf("服务器内部错误: %v, path: %s", recovered, c.Request.URL.Path)
|
|
|
|
respondError(c, http.StatusInternalServerError, "INTERNAL_ERROR",
|
|
"服务器内部错误", recovered)
|
|
})
|
|
}
|