commit 719f79ffd80a52e76c460c42bf01b87efbeaa017 Author: yangbowen Date: Wed Jan 3 15:17:14 2024 +0800 token验证解析 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0f57925 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.tsl3060.com/openapi/go-security + +go 1.21 + +require github.com/dgrijalva/jwt-go v3.2.0+incompatible diff --git a/jwt/jwt.go b/jwt/jwt.go new file mode 100644 index 0000000..2dfce60 --- /dev/null +++ b/jwt/jwt.go @@ -0,0 +1,55 @@ +package jwt + +import ( + "embed" + "errors" + "fmt" + "github.com/dgrijalva/jwt-go" +) + +// TokenData 用于存储解析的 token 数据 +type TokenData struct { + Expired float64 + Frequency float64 +} + +var publicKeyEmbed embed.FS + +// VerifyToken 解析并验证 JWT,返回 TokenData 或错误 +func VerifyToken(tokenString string) (*TokenData, error) { + // 从文件中读取公钥 + publicKeyPem, err := publicKeyEmbed.ReadFile("server_public_key.pem") + if err != nil { + return nil, fmt.Errorf("加载公钥失败: %v", err) + } + + publicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKeyPem) + if err != nil { + return nil, fmt.Errorf("解析公钥失败: %v", err) + } + + // 解析并验证 JWT + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + return 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("无效令牌") + } +} diff --git a/jwt/server_public_key.pem b/jwt/server_public_key.pem new file mode 100644 index 0000000..a01136a --- /dev/null +++ b/jwt/server_public_key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuZ63ry9k3F2WExbOqaM7 +Kuacqt7U4ja5x6BomSoMp2TpgTRXOvTAMH+etRkqKDDPoHoNl23vryPQpx6v4tLn +7onqhBexGV8EWjWyWkBOGI9LBvhjG5eWWwisnpUNlbeYUBanzxJEm6Fx0hqKK7Xy +OXiwA0FotL7OEhfHaTEsp18EXkGSih9tZejLU5GITH26h/9sAz9Frdwe6NhZm712 +s8H7r63/ecd522JHqdVbmg7nj0dCwJ5fWLx1pnbDfaGD8PR7sfRSWs6f2NHBKgRk +8sdD4l7Q38bpBIwhAjRiwWsj3+RQhS5BoTjunvysrMS1J6/nfQi97yJoedWUz2DS +BQIDAQAB +-----END PUBLIC KEY----- \ No newline at end of file