Sfoglia il codice sorgente

调用mcp微服务测试通过

qdy 1 mese fa
parent
commit
f2dfcc15af

+ 0
- 81
auth/token_auth_middleware.go Vedi File

1
-package auth
2
-
3
-import (
4
-	"net/http"
5
-	"strings"
6
-
7
-	"git.x2erp.com/qdy/go-base/config"
8
-	"git.x2erp.com/qdy/go-base/ctx"
9
-	"git.x2erp.com/qdy/go-base/logger"
10
-)
11
-
12
-// // 全局配置(单例)
13
-// var appConfig config.IConfig
14
-
15
-// // ResponseFormat 响应格式
16
-// type ResponseFormat int
17
-
18
-// const (
19
-// 	FormatJSON ResponseFormat = iota
20
-// 	FormatCSV
21
-// )
22
-
23
-// // JWTAuthMiddlewareInit 初始化中间件配置
24
-// func JWTAuthMiddlewareInit(config config.IConfig) {
25
-// 	appConfig = config
26
-// }
27
-
28
-// JWT认证中间件(支持指定响应格式)
29
-func TokenAuth(next http.Handler) http.Handler {
30
-	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31
-
32
-		// 从Header获取Authorization
33
-		authHeader := r.Header.Get("Authorization")
34
-
35
-		// 检查Authorization头是否存在
36
-		if authHeader == "" {
37
-			unauthorized(w, "Authorization header is required")
38
-
39
-		}
40
-
41
-		// 检查Bearer格式
42
-		if !strings.HasPrefix(authHeader, "Bearer ") {
43
-			unauthorized(w, "Authorization header must start with 'Bearer '")
44
-
45
-		}
46
-
47
-		token := strings.TrimPrefix(authHeader, "Bearer ")
48
-
49
-		// 验证JWT令牌
50
-		if !isValidToken(token) {
51
-			unauthorized(w, "Invalid token")
52
-		}
53
-
54
-		appConfig := config.GetConfig()
55
-		//保存上下文
56
-		// 创建LoggerContext(从token解析用户信息)
57
-		requestContext := &ctx.RequestContext{
58
-			ServiceName:  appConfig.GetServiceConfig().ServiceName,
59
-			InstanceName: appConfig.GetServiceConfig().InstanceName,
60
-			TraceID:      "trace_id-123", // 生成追踪ID
61
-			TenantID:     "tenant-123",   // 从token解析
62
-			UserID:       "user-456",     // 从token解析
63
-		}
64
-
65
-		if logger.IsDebug() {
66
-			logger.DebugC(requestContext, "Before save requestContext: %+v", requestContext)
67
-		}
68
-
69
-		// 保存到请求
70
-		r = ctx.SaveContext(r, requestContext)
71
-		// 继续处理请求
72
-		next.ServeHTTP(w, r)
73
-	})
74
-}
75
-
76
-// 验证令牌(需要根据实际项目实现)
77
-func isValidToken(token string) bool {
78
-	// TODO: 实现真正的JWT验证逻辑
79
-	// 暂时简化处理
80
-	return token != ""
81
-}

auth/basic_auth_middewara.go → authbase/basic_auth_middewara.go Vedi File

1
-package auth
1
+package authbase
2
 
2
 
3
 import (
3
 import (
4
 	"encoding/base64"
4
 	"encoding/base64"

auth/error_unauthorized.go → authbase/error_unauthorized.go Vedi File

1
-package auth
1
+package authbase
2
 
2
 
3
 import (
3
 import (
4
 	"encoding/json"
4
 	"encoding/json"
23
 	json.NewEncoder(w).Encode(response)
23
 	json.NewEncoder(w).Encode(response)
24
 
24
 
25
 	// 记录日志
25
 	// 记录日志
26
-	logger.Warn("Basic认证失败: %s", message)
26
+	logger.Warn("认证失败: %s", message)
27
 }
27
 }

+ 72
- 0
authbase/token_auth_middleware.go Vedi File

1
+package authbase
2
+
3
+import (
4
+	"fmt"
5
+	"net/http"
6
+	"strings"
7
+	"time"
8
+
9
+	"git.x2erp.com/qdy/go-base/config"
10
+	"git.x2erp.com/qdy/go-base/ctx"
11
+	"git.x2erp.com/qdy/go-base/util/jwt"
12
+)
13
+
14
+// TokenAuth 简化的Bearer认证中间件
15
+func TokenAuth(next http.Handler) http.Handler {
16
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17
+		// 1. 检查认证头
18
+		authHeader := r.Header.Get("Authorization")
19
+		if authHeader == "" {
20
+			unauthorized(w, "缺少认证信息")
21
+			return
22
+		}
23
+
24
+		// 2. 检查Basic格式
25
+		if !strings.HasPrefix(authHeader, "Bearer ") {
26
+			unauthorized(w, "认证格式错误,请使用Bearer认证")
27
+			return
28
+		}
29
+
30
+		// 3. 解码凭证
31
+		token := strings.TrimPrefix(authHeader, "Bearer ")
32
+
33
+		// 验证JWT令牌
34
+		claims, err := validToken(token)
35
+		if err != nil {
36
+
37
+			unauthorized(w, fmt.Sprintf("Invalid token: %v", err))
38
+		}
39
+
40
+		// 6. 创建请求上下文
41
+		traceID := r.Header.Get("X-Trace-ID")
42
+		if traceID == "" {
43
+			// 生成简单的时间戳追踪ID
44
+			traceID = time.Now().Format("20060102150405.000")
45
+		}
46
+
47
+		cfg := config.GetConfig()
48
+
49
+		requestCtx := &ctx.RequestContext{
50
+			ServiceName:  cfg.GetServiceConfig().ServiceName,
51
+			InstanceName: cfg.GetServiceConfig().InstanceName,
52
+			TraceID:      traceID,
53
+			TenantID:     claims.TenantID,
54
+			UserID:       claims.UserID,
55
+			Username:     claims.Username,
56
+			ProjectID:    claims.ProjectID,
57
+		}
58
+
59
+		// 7. 保存到请求
60
+		r = ctx.SaveContext(r, requestCtx)
61
+
62
+		// 8. 继续处理
63
+		next.ServeHTTP(w, r)
64
+	})
65
+}
66
+
67
+// 验证令牌(需要根据实际项目实现)
68
+func validToken(token string) (*jwt.Claims, error) {
69
+	secretKey := config.GetServiceConfig().SecretKey
70
+	//logger.Debug("secretKey:%s", secretKey)
71
+	return jwt.ParseToken(token, secretKey)
72
+}

+ 16
- 0
ctx/request_context.go Vedi File

52
 	return &RequestContext{}
52
 	return &RequestContext{}
53
 }
53
 }
54
 
54
 
55
+// FromContext 从 context.Context 中提取 RequestContext
56
+func FromContext(ctx context.Context) *RequestContext {
57
+	if ctx == nil {
58
+		return &RequestContext{}
59
+	}
60
+
61
+	if v := ctx.Value(loggerKey); v != nil {
62
+		if reqCtx, ok := v.(*RequestContext); ok {
63
+			return reqCtx
64
+		}
65
+	}
66
+
67
+	return &RequestContext{}
68
+}
69
+
55
 func GetContextTest() *RequestContext {
70
 func GetContextTest() *RequestContext {
56
 
71
 
57
 	return &RequestContext{
72
 	return &RequestContext{
61
 		InstanceName: "test-InstanceName",
76
 		InstanceName: "test-InstanceName",
62
 		UserID:       "test-UserID",
77
 		UserID:       "test-UserID",
63
 		Username:     "test-Username",
78
 		Username:     "test-Username",
79
+		ProjectID:    "test-ProjectID",
64
 	}
80
 	}
65
 }
81
 }

+ 7
- 0
model/request/configreq/config_requset_model.go Vedi File

10
 	YamlName  string `json:"yaml_name," binding:"required"`
10
 	YamlName  string `json:"yaml_name," binding:"required"`
11
 	YamlValue string `json:"yaml_value" binding:"required"`
11
 	YamlValue string `json:"yaml_value" binding:"required"`
12
 }
12
 }
13
+
14
+// ConfigTokenRequest 创建配置中心Token参数
15
+type ConfigTokenRequest struct {
16
+	ServiceName string `json:"service_name," binding:"required"`
17
+	ProjectID   string `json:"project_id," binding:"required"`
18
+	ExpiresDays int    `json:"expires_days" binding:"required"`
19
+}

+ 1
- 0
util/jwt/jwt_util.go Vedi File

30
 // expiresDays: 过期天数(优先使用)
30
 // expiresDays: 过期天数(优先使用)
31
 // secretKey: 密钥
31
 // secretKey: 密钥
32
 func CreateTokenDays(claims *Claims, expiresDays int, secretKey string) (string, error) {
32
 func CreateTokenDays(claims *Claims, expiresDays int, secretKey string) (string, error) {
33
+	//logger.Debug("secretKey:%s", secretKey)
33
 	return createTokenInternal(claims, expiresDays, 0, secretKey)
34
 	return createTokenInternal(claims, expiresDays, 0, secretKey)
34
 }
35
 }
35
 
36
 

Loading…
Annulla
Salva