tianyuan-api-server/pkg/jwt/jwtx.go
2024-10-02 00:57:17 +08:00

69 lines
1.7 KiB
Go
Raw 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 jwtx
import (
"errors"
"github.com/golang-jwt/jwt/v4"
"strconv"
"time"
)
// Token 生成逻辑的函数,接收 userId、过期时间和密钥返回生成的 token
func GenerateJwtToken(userId int64, secret string, expireTime int64) (string, error) {
// 获取当前时间戳
now := time.Now().Unix()
// 定义 JWT Claims
claims := jwt.MapClaims{
"exp": now + expireTime, // token 过期时间
"iat": now, // 签发时间
"userId": userId, // 用户ID
}
// 创建新的 JWT token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// 使用密钥对 token 签名
signedToken, err := token.SignedString([]byte(secret))
if err != nil {
return "", err
}
return signedToken, nil
}
func ParseJwtToken(tokenStr string, secret string) (int64, error) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil || !token.Valid {
return 0, errors.New("invalid JWT")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return 0, errors.New("invalid JWT claims")
}
// 从 claims 中提取 userId
userIdRaw, ok := claims["userId"]
if !ok {
return 0, errors.New("userId not found in JWT")
}
// 处理不同类型的 userId确保它被转换为 int64
switch userId := userIdRaw.(type) {
case float64:
return int64(userId), nil
case int64:
return userId, nil
case string:
// 如果 userId 是字符串,可以尝试将其转换为 int64
parsedId, err := strconv.ParseInt(userId, 10, 64)
if err != nil {
return 0, errors.New("invalid userId in JWT")
}
return parsedId, nil
default:
return 0, errors.New("unsupported userId type in JWT")
}
}