commit
719f79ffd8
@ -0,0 +1,5 @@ |
||||
module git.tsl3060.com/openapi/go-security |
||||
|
||||
go 1.21 |
||||
|
||||
require github.com/dgrijalva/jwt-go v3.2.0+incompatible |
@ -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("无效令牌") |
||||
} |
||||
} |
@ -0,0 +1,9 @@ |
||||
-----BEGIN PUBLIC KEY----- |
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuZ63ry9k3F2WExbOqaM7 |
||||
Kuacqt7U4ja5x6BomSoMp2TpgTRXOvTAMH+etRkqKDDPoHoNl23vryPQpx6v4tLn |
||||
7onqhBexGV8EWjWyWkBOGI9LBvhjG5eWWwisnpUNlbeYUBanzxJEm6Fx0hqKK7Xy |
||||
OXiwA0FotL7OEhfHaTEsp18EXkGSih9tZejLU5GITH26h/9sAz9Frdwe6NhZm712 |
||||
s8H7r63/ecd522JHqdVbmg7nj0dCwJ5fWLx1pnbDfaGD8PR7sfRSWs6f2NHBKgRk |
||||
8sdD4l7Q38bpBIwhAjRiwWsj3+RQhS5BoTjunvysrMS1J6/nfQi97yJoedWUz2DS |
||||
BQIDAQAB |
||||
-----END PUBLIC KEY----- |
Loading…
Reference in new issue