tydata-server/app/main/api/internal/middleware/authinterceptormiddleware.go

55 lines
1.2 KiB
Go
Raw Normal View History

2025-06-08 15:07:04 +08:00
package middleware
import (
"context"
"net/http"
2025-06-08 15:14:34 +08:00
"tydata-server/app/main/api/internal/config"
2025-06-08 15:07:04 +08:00
jwtx "tydata-server/common/jwt"
"tydata-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/rest/httpx"
)
const (
// 定义错误码
ErrCodeUnauthorized = 401
)
type AuthInterceptorMiddleware struct {
Config config.Config
}
func NewAuthInterceptorMiddleware(c config.Config) *AuthInterceptorMiddleware {
return &AuthInterceptorMiddleware{
Config: c,
}
}
func (m *AuthInterceptorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 从请求头中获取Authorization字段
authHeader := r.Header.Get("Authorization")
// 如果没有Authorization头直接放行
if authHeader == "" {
next(w, r)
return
}
// 解析JWT令牌
2025-06-18 16:31:32 +08:00
claims, err := jwtx.ParseJwtToken(authHeader, m.Config.JwtAuth.AccessSecret)
2025-06-08 15:07:04 +08:00
if err != nil {
// JWT解析失败返回401错误
httpx.Error(w, errors.Wrapf(xerr.NewErrCode(ErrCodeUnauthorized), "token解析失败: %v", err))
return
}
2025-06-18 16:31:32 +08:00
ctx := context.WithValue(r.Context(), jwtx.ExtraKey, claims)
2025-06-08 15:07:04 +08:00
// 使用新的上下文继续处理请求
next(w, r.WithContext(ctx))
}
}