package middleware import ( "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt" "go_api_tmpl/core" "go_api_tmpl/global" "go_api_tmpl/utils" "net/http" ) // AuthorizeJWT 验证JWT func AuthorizeJWT() gin.HandlerFunc { return func(ctx *gin.Context) { const BearerSchema string = "Bearer " authHeader := ctx.GetHeader("Authorization") if authHeader == "" { core.R(ctx).FailWithMessageAndCode("请先登录", http.StatusUnauthorized) ctx.Abort() return } tokenString := authHeader[len(BearerSchema):] if token, err := utils.ValidateToken(tokenString); err != nil { global.Log.Errorf("Token校验失败: %v ------> %v", tokenString, err.Error()) core.R(ctx).FailWithMessageAndCode("Token校验失败", http.StatusUnauthorized) return } else { if claims, ok := token.Claims.(jwt.MapClaims); !ok { ctx.AbortWithStatus(http.StatusUnauthorized) } else { if token.Valid { ctx.Set("userId", claims["userId"]) } else { ctx.AbortWithStatus(http.StatusUnauthorized) } } } } }