| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package authbase
-
- import (
- "fmt"
- "net/http"
- "strings"
- "time"
-
- "git.x2erp.com/qdy/go-base/config"
- "git.x2erp.com/qdy/go-base/ctx"
- "git.x2erp.com/qdy/go-base/util/jwt"
- )
-
- // TokenAuth 简化的Bearer认证中间件
- func TokenAuth(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // 1. 检查认证头
- authHeader := r.Header.Get("Authorization")
- if authHeader == "" {
- unauthorized(w, "缺少认证信息")
- return
- }
-
- // 2. 检查Basic格式
- if !strings.HasPrefix(authHeader, "Bearer ") {
- unauthorized(w, "认证格式错误,请使用Bearer认证")
- return
- }
-
- // 3. 解码凭证
- token := strings.TrimPrefix(authHeader, "Bearer ")
-
- // 验证JWT令牌
- claims, err := validToken(token)
- if err != nil {
-
- unauthorized(w, fmt.Sprintf("Invalid token: %v", err))
- }
-
- // 6. 创建请求上下文
- traceID := r.Header.Get("X-Trace-ID")
- if traceID == "" {
- // 生成简单的时间戳追踪ID
- traceID = time.Now().Format("20060102150405.000")
- }
-
- cfg := config.GetConfig()
-
- requestCtx := &ctx.RequestContext{
- ServiceName: cfg.GetServiceConfig().ServiceName,
- InstanceName: cfg.GetServiceConfig().InstanceName,
- TraceID: traceID,
- TenantID: claims.TenantID,
- UserID: claims.UserID,
- Username: claims.Username,
- ProjectID: claims.ProjectID,
- }
-
- // 7. 保存到请求
- r = ctx.SaveContext(r, requestCtx)
-
- // 8. 继续处理
- next.ServeHTTP(w, r)
- })
- }
-
- // 验证令牌(需要根据实际项目实现)
- func validToken(token string) (*jwt.Claims, error) {
- secretKey := config.GetServiceConfig().SecretKey
- //logger.Debug("secretKey:%s", secretKey)
- return jwt.ParseToken(token, secretKey)
- }
|