package middleware import ( "net/http" "strings" "github.com/gin-gonic/gin" "newaterobot-process/service" ) // JWTAuthMiddleware JWT认证中间件 func JWTAuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // 获取token authHeader := c.GetHeader("Authorization") if authHeader == "" { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "message": "请求未携带token,无权限访问", }) c.Abort() return } // 按空格分割 parts := strings.SplitN(authHeader, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "message": "请求头中auth格式有误", }) c.Abort() return } // 解析token claims, err := service.GetJWTService().ParseToken(parts[1]) if err != nil { c.JSON(http.StatusUnauthorized, gin.H{ "code": 401, "message": "token无效或已过期", }) c.Abort() return } // 将用户信息保存到上下文 c.Set("user_id", claims.UserID) c.Set("username", claims.Username) c.Next() } }