package jwt import ( "crypto/rsa" "errors" "fmt" "github.com/dgrijalva/jwt-go" ) // TokenService 是用于 JWT 操作的服务 type TokenService struct { publicKey *rsa.PublicKey } // NewTokenService 创建一个新的 TokenService 实例 func NewTokenService(publicKeyString string) (*TokenService, error) { publicKey, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKeyString)) if err != nil { return nil, fmt.Errorf("解析公钥失败: %v", err) } return &TokenService{ publicKey: publicKey, }, nil } // TokenData 用于存储解析的 token 数据 type TokenData struct { Expired float64 Frequency float64 } // VerifyToken 解析并验证 JWT,返回 TokenData 或错误 func (j *TokenService) VerifyToken(tokenString string) (*TokenData, error) { // 解析并验证 JWT token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { return j.publicKey, nil }) if err != nil { return nil, fmt.Errorf("令牌解析失败: %v", err) } if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { expired, okExp := claims["expired"].(float64) frequency, okFreq := claims["frequency"].(float64) if !okExp || !okFreq { return nil, errors.New("无效的令牌负载") } return &TokenData{ Expired: expired, Frequency: frequency, }, nil } else { return nil, errors.New("无效令牌") } }