Files
huangjin fe3ad20fe2 'init'
2026-06-29 17:34:59 +08:00

46 lines
1.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"strings"
"com.sclktx/m/v2/internal/common/response"
"com.sclktx/m/v2/internal/common/utils"
"github.com/gin-gonic/gin"
)
// JWTAuth JWT 认证中间件
// 1. 从 Authorization header 提取 Bearer Token
// 2. 解析验证 JWT签名 + 过期时间)
// 3. 将 user_id、role_code、role_codes 注入 gin.Context
// 4. 后续 Handler 通过 utils.GetUserID(c) / utils.GetRoleCodes(c) 获取
func JWTAuth(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
response.Unauthorized(c, "未提供认证令牌")
c.Abort()
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
response.Unauthorized(c, "认证格式错误")
c.Abort()
return
}
claims, err := utils.ParseToken(parts[1], secret)
if err != nil {
response.Unauthorized(c, "认证令牌无效或已过期")
c.Abort()
return
}
// 注入用户信息到 Context
c.Set("user_id", claims.UserID)
c.Set("role_code", claims.RoleCode)
c.Next()
}
}