middleware.go 721 B

12345678910111213141516171819202122
  1. package mcp
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/beego/beego/v2/server/web"
  6. beegoContext "github.com/beego/beego/v2/server/web/context"
  7. )
  8. // AuthMiddleware 返回一个中间件函数,用于验证MCP请求中的认证令牌
  9. func AuthMiddleware(ctx *beegoContext.Context) {
  10. presetMcpApiKey := web.AppConfig.DefaultString("mcp_api_key", "")
  11. mcpApiKeyParamValue := ctx.Request.URL.Query().Get("api_key")
  12. if presetMcpApiKey != mcpApiKeyParamValue {
  13. http.Error(ctx.ResponseWriter, "Missing or invalid mcp authorization key", http.StatusUnauthorized)
  14. return
  15. }
  16. // Add mcp_api_key to request context
  17. ctx.Request.WithContext(context.WithValue(ctx.Request.Context(), "mcp_api_key", mcpApiKeyParamValue))
  18. }