go-jwt令牌验证错误 – 令牌签名无效:密钥类型无效

huangapple go评论102阅读模式
英文:

go-jwt token validation error - token signature is invalid: key is of invalid type

问题

获取错误

> 令牌签名无效:密钥类型无效

尝试验证JWT令牌时出现此错误。使用golang-jwt(v5)库。

以下是我生成令牌的方式:

const (
    secretKey     = "162475e134198bd451af0b88a5defe132c72cb26fd58449772883b90c498b484"
	tokenLifespan = 4
)

func GenerateToken() (string, error) {
    claims := jwt.MapClaims{}
	claims["authorized"] = true
    claims["foo"] = "bar"
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(tokenLifespan)).Unix()
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	return token.SignedString([]byte(secretKey))
}

这是生成的令牌:
go-jwt令牌验证错误 – 令牌签名无效:密钥类型无效

这是我验证令牌的方式:

func ValidateToken(c *gin.Context) error {
	token, err := GetToken(c)

	if err != nil {
		return err
	}

	_, ok := token.Claims.(jwt.MapClaims)
	if ok && token.Valid {
		return nil
	}

	return errors.New("invalid token provided")
}

func GetToken(c *gin.Context) (*jwt.Token, error) {
	tokenString := getTokenFromRequest(c)
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		return token, nil
	})
	return token, err
}

func getTokenFromRequest(c *gin.Context) string {
	bearerToken := c.Request.Header.Get("Authorization")

	splitToken := strings.Split(bearerToken, " ")
	if len(splitToken) == 2 {
		return splitToken[1]
	}
	return ""
}

有什么建议可以使其正常工作吗?我漏掉了什么?谢谢。

英文:

Getting an error

> token signature is invalid: key is of invalid type

When trying to validate JWT token. Using golang-jwt (v5) library.

Here is how I'm generating a token:

const (
    secretKey     = "162475e134198bd451af0b88a5defe132c72cb26fd58449772883b90c498b484"
	tokenLifespan = 4
)

func GenerateToken() (string, error) {
    claims := jwt.MapClaims{}
	claims["authorized"] = true
    claims["foo"] = "bar"
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(tokenLifespan)).Unix()
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	return token.SignedString([]byte(secretKey))
}

Here is the generated token:
go-jwt令牌验证错误 – 令牌签名无效:密钥类型无效

And here is how I'm validating the token:

func ValidateToken(c *gin.Context) error {
	token, err := GetToken(c)

	if err != nil {
		return err
	}

	_, ok := token.Claims.(jwt.MapClaims)
	if ok && token.Valid {
		return nil
	}

	return errors.New("invalid token provided")
}

func GetToken(c *gin.Context) (*jwt.Token, error) {
	tokenString := getTokenFromRequest(c)
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}

		return token, nil
	})
	return token, err
}

func getTokenFromRequest(c *gin.Context) string {
	bearerToken := c.Request.Header.Get("Authorization")

	splitToken := strings.Split(bearerToken, " ")
	if len(splitToken) == 2 {
		return splitToken[1]
	}
	return ""
}

Any suggestions how to get it working? What am I missing? Thanks.

答案1

得分: 1

Keyfunc 是由 Parse 方法使用的回调函数,用于提供用于验证的密钥。因此,它应该返回一个密钥,而不是参数 token *jwt.Token

  token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  	if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  		return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  	}

- 	return token, nil
+ 	return []byte(secretKey), nil
  })
英文:

The Keyfunc is used by the Parse methods as a callback function to supply the key for verification. So it should return a key instead of the parameter token *jwt.Token.

  token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  	if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  		return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  	}

- 	return token, nil
+ 	return []byte(secretKey), nil
  })

答案2

得分: 1

在函数GetToken()中,jwt.Parse的返回值必须是(tokenString, func(token) (secretKey, error)

所以要修复你的代码,将:

return token, nil

改为

return []byte(secretKey), nil
英文:

In function GetToken(). Return of jwt.Parse must be (tokenString, func(token) (secretKey, error)

So to fix your code, change:

return token, nil

to

return []byte(secretKey), nil

huangapple
  • 本文由 发表于 2023年7月28日 07:40:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76784035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定