49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
|
|
package mildware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"gen2d/internal/model"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
"github.com/golang-jwt/jwt/v5"
|
||
|
|
)
|
||
|
|
|
||
|
|
// AuthMiddleware 返回 JWT 认证中间件,校验 Bearer token 并注入 userID 到上下文。
|
||
|
|
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
authHeader := c.GetHeader("Authorization")
|
||
|
|
if authHeader == "" {
|
||
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "未提供认证令牌"))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||
|
|
if tokenString == authHeader {
|
||
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "认证格式错误,需为 Bearer <token>"))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
||
|
|
return []byte(jwtSecret), nil
|
||
|
|
})
|
||
|
|
if err != nil || !token.Valid {
|
||
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌无效或已过期"))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
||
|
|
if !ok {
|
||
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌解析失败"))
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
if sub, ok := claims["sub"]; ok {
|
||
|
|
c.Set("userID", sub)
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|