修复jwt解析异常

This commit is contained in:
骑着蜗牛追导弹 2024-02-05 10:38:01 +08:00
parent 3bf135552b
commit d47287adb4
2 changed files with 38 additions and 50 deletions

View File

@ -15,13 +15,14 @@ func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
color.Green("============ 进入鉴权中间件 ============") color.Green("============ 进入鉴权中间件 ============")
token := c.Request.Header.Get("Authorization") token := c.Request.Header.Get("Authorization")
color.Green("JWT Token: %s", token)
if util.IsBlank(token) { if util.IsBlank(token) {
c.JSON(http.StatusUnauthorized, resp.NoLoginError) c.JSON(http.StatusUnauthorized, resp.NoLoginError)
c.Abort() c.Abort()
return return
} }
color.Green("============ 解析token ============") color.Green("============ 解析token ============")
if code, claims := ParseToken(token); code == -1 { if claims, err := ParseToken(token); err != nil {
c.JSON(http.StatusUnauthorized, resp.NoLoginError) c.JSON(http.StatusUnauthorized, resp.NoLoginError)
c.Abort() c.Abort()
} else { } else {

View File

@ -2,6 +2,7 @@ package jwt
import ( import (
"d2-admin-service/src/infra/config" "d2-admin-service/src/infra/config"
"errors"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"time" "time"
@ -14,60 +15,46 @@ type CustomClaims struct {
} }
// GenToken 生成token // GenToken 生成token
func GenToken(username string) string { func GenToken(username string) (tokenString string, err error) {
secret := config.Config.Jwt.Secret secret := []byte(config.Config.Jwt.Secret)
// 私钥用于HS256签名时用作secret对于RS256等非对称算法则是私钥 claim := CustomClaims{
key := []byte(secret)
// 生成claims
claims := &CustomClaims{
RegisteredClaims: jwt.RegisteredClaims{ RegisteredClaims: jwt.RegisteredClaims{
Issuer: "odboy.cn", ExpiresAt: jwt.NewNumericDate(time.Now().Add(3 * time.Hour * time.Duration(1))), // 过期时间3小时
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24)), // 设置过期时间 IssuedAt: jwt.NewNumericDate(time.Now()), // 签发时间
Subject: username, // 用户ID或其他唯一标识符 NotBefore: jwt.NewNumericDate(time.Now()), // 生效时间
IssuedAt: jwt.NewNumericDate(time.Now()),
}, },
Username: username, Username: username,
} }
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim) // 使用HS256算法
// 创建一个新的token对象 tokenString, err = token.SignedString(secret)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) color.Green("%s Generated JWT: %s\n", username, tokenString)
// 使用密钥进行签名并获取完整的编码后的token return tokenString, err
signedToken, err := token.SignedString(key)
if err != nil {
panic("Generated JWT Error: " + err.Error())
}
color.Green("%s Generated JWT: %s\n", username, signedToken)
return signedToken
} }
// ParseToken 解析token func getSecret() jwt.Keyfunc {
func ParseToken(signedToken string) (int, *CustomClaims) { return func(token *jwt.Token) (interface{}, error) {
// 解析JWT return []byte(config.Config.Jwt.Secret), nil
parser := jwt.Parser{}
// 需要设置Valid方法以验证claims中的标准字段例如ExpiresAt
var parsedClaims *CustomClaims // 将parsedClaims声明为指针类型
_, _, err := parser.ParseUnverified(signedToken, parsedClaims)
if err != nil {
//panic("无效Token" + err.Error())
color.Red("无效token, %v\n", err)
return -1, nil
} }
// 如果需要验证签名,请使用正确的秘钥和方法 }
secret := config.Config.Jwt.Secret
key := []byte(secret) func ParseToken(tokenString string) (*CustomClaims, error) {
verifiedToken, err := parser.Parse(signedToken, func(token *jwt.Token) (interface{}, error) { token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, getSecret())
return key, nil if err != nil {
}) var ve *jwt.ValidationError
if err != nil { if errors.As(err, &ve) {
color.Red("无效token, %v\n", err) if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return -1, nil return nil, errors.New("that's not even a token")
} } else if ve.Errors&jwt.ValidationErrorExpired != 0 {
parsedClaims, ok := verifiedToken.Claims.(*CustomClaims) return nil, errors.New("token is expired")
if !ok || !verifiedToken.Valid { } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
//panic("Invalid token") return nil, errors.New("token not active yet")
color.Red("token未通过校验, %v\n", err) } else {
return -1, nil return nil, errors.New("couldn't handle this token")
} }
return 200, parsedClaims }
}
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("couldn't handle this token")
} }