65 lines
1.6 KiB
Go
65 lines
1.6 KiB
Go
|
package jwtx
|
|||
|
|
|||
|
import (
|
|||
|
"context"
|
|||
|
"errors"
|
|||
|
"fmt"
|
|||
|
"time"
|
|||
|
|
|||
|
"github.com/golang-jwt/jwt/v4"
|
|||
|
)
|
|||
|
|
|||
|
// Token 生成逻辑的函数,接收 userId、过期时间和密钥,返回生成的 token
|
|||
|
func GenerateJwtTokenV2(claims map[string]interface{}, secret string, expireTime int64) (string, error) {
|
|||
|
// 获取当前时间戳
|
|||
|
now := time.Now().Unix()
|
|||
|
// 定义 JWT Claims
|
|||
|
claimsMap := jwt.MapClaims{
|
|||
|
"exp": now + expireTime, // token 过期时间
|
|||
|
"iat": now, // 签发时间
|
|||
|
"claims": claims, // 自定义claims
|
|||
|
}
|
|||
|
|
|||
|
// 创建新的 JWT token
|
|||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claimsMap)
|
|||
|
|
|||
|
// 使用密钥对 token 签名
|
|||
|
signedToken, err := token.SignedString([]byte(secret))
|
|||
|
if err != nil {
|
|||
|
return "", err
|
|||
|
}
|
|||
|
|
|||
|
return signedToken, nil
|
|||
|
}
|
|||
|
func ParseJwtTokenV2(tokenStr string, secret string) (map[string]interface{}, error) {
|
|||
|
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
|
|||
|
return []byte(secret), nil
|
|||
|
})
|
|||
|
|
|||
|
if err != nil || !token.Valid {
|
|||
|
return nil, errors.New("invalid JWT")
|
|||
|
}
|
|||
|
|
|||
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|||
|
if !ok || !token.Valid {
|
|||
|
return nil, errors.New("invalid JWT claims")
|
|||
|
}
|
|||
|
|
|||
|
// 从 claims 中提取 userId
|
|||
|
claimsRaw, ok := claims["claims"]
|
|||
|
if !ok {
|
|||
|
return nil, errors.New("claims not found in JWT")
|
|||
|
}
|
|||
|
|
|||
|
return claimsRaw.(map[string]interface{}), nil
|
|||
|
}
|
|||
|
|
|||
|
func GetJwtClaims(ctx context.Context) (map[string]interface{}, error) {
|
|||
|
// 尝试从上下文中获取 jwtUserId
|
|||
|
claims, ok := ctx.Value("claims").(map[string]interface{})
|
|||
|
if !ok {
|
|||
|
return nil, fmt.Errorf("无法获取jwt claims: %v", claims)
|
|||
|
}
|
|||
|
return claims, nil
|
|||
|
}
|