From 191ea5389eb1acc3ac9456802d7ad03c38c92de7 Mon Sep 17 00:00:00 2001 From: KynixInHK Date: Wed, 10 Jul 2024 12:01:18 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=87JWT=E5=8D=87=E6=A0=BC=E7=82=BARSA?= =?UTF-8?q?=E7=B0=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- am_jwt/jwt.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/am_jwt/jwt.go b/am_jwt/jwt.go index 5827eef..7b88a06 100644 --- a/am_jwt/jwt.go +++ b/am_jwt/jwt.go @@ -117,9 +117,15 @@ func GenToken(claims *TokenClaims) (string, error) { Issuer: claims.Issuer, // 签发人 } + // 解析私鑰 + privKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(claims.SECRET)) + if err != nil { + return "", err + } + // 生成token字串 tokenGenerator := jwt.NewWithClaims(jwt.SigningMethodHS256, tokenClaims) - token, err := tokenGenerator.SignedString([]byte(claims.SECRET)) // 生成token + token, err := tokenGenerator.SignedString(privKey) // 生成token if err != nil { return "", err } @@ -147,9 +153,15 @@ func GenToken(claims *TokenClaims) (string, error) { * 3. secret string:解码密钥 */ func ParseToken(token string, roleRequired int, secret string) (*TokenClaims, error) { + // 解析公鑰 + pem, err := jwt.ParseRSAPublicKeyFromPEM([]byte(secret)) + if err != nil { + return nil, err + } + // 解析token result, err := jwt.ParseWithClaims(token, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte(secret), nil + return pem, nil }) // 解析出现问题 @@ -195,7 +207,7 @@ func ParseToken(token string, roleRequired int, secret string) (*TokenClaims, er if ClaimToRole(claims.Role) >= roleRequired { // 如果提供的token权限验证大于所需权限,初步判断通过 if roleRequired == 1 && ClaimToRole(claims.Role) == 2 { // user权限无权新增用户 return nil, InvalidRoleError - } + } // user不允許操作temp if ClaimToRole(claims.Role) == 1 { // temp权限仅用于注册和重设密码临时使用,一经使用立即灭活 _, err := Kickoff(token)