73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/golang-jwt/jwt/v5"
|
||
)
|
||
|
||
type Claims struct {
|
||
UserID string `json:"userId"`
|
||
jwt.RegisteredClaims
|
||
}
|
||
|
||
// GenerateToken 生成 JWT Token(7 天有效期)
|
||
func GenerateToken(userID, secret string) (string, error) {
|
||
claims := Claims{
|
||
UserID: userID,
|
||
RegisteredClaims: jwt.RegisteredClaims{
|
||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
|
||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||
},
|
||
}
|
||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
return token.SignedString([]byte(secret))
|
||
}
|
||
|
||
// AuthRequired JWT 认证中间件(默认所有路由需要认证)
|
||
func AuthRequired(secret string) gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
authHeader := c.GetHeader("Authorization")
|
||
if authHeader == "" {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||
"code": 401,
|
||
"message": "缺少认证令牌",
|
||
})
|
||
return
|
||
}
|
||
|
||
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
||
if tokenStr == authHeader {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||
"code": 401,
|
||
"message": "令牌格式错误",
|
||
})
|
||
return
|
||
}
|
||
|
||
claims := &Claims{}
|
||
token, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (any, error) {
|
||
return []byte(secret), nil
|
||
})
|
||
if err != nil || !token.Valid {
|
||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||
"code": 401,
|
||
"message": "令牌无效或已过期",
|
||
})
|
||
return
|
||
}
|
||
|
||
c.Set("userID", claims.UserID)
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// GetUserID 从上下文中获取当前用户 ID
|
||
func GetUserID(c *gin.Context) string {
|
||
uid, _ := c.Get("userID")
|
||
return uid.(string)
|
||
}
|