简体   繁体   English

使用 jwt-go 库 - 密钥无效或类型无效

[英]Using jwt-go Library - Key is invalid or invalid type

I am trying to pass in a token to the "Parse(token String, keyFunc Keyfunc)" GO routine defined in this GO-library ( http://godoc.org/github.com/dgrijalva/jwt-go ) for JWT-token parsing/validation.我正在尝试将令牌传递给此 GO-library ( http://godoc.org/github.com/dgrijalva/jwt-go ) 中定义的“Parse(token String, keyFunc Keyfunc)”GO 例程,用于 JWT-令牌解析/验证。

When I pass the token to this function -当我将令牌传递给这个 function -

token, err := jwt.Parse(getToken, func(token *jwt.Token) (interface{}, error) {
        return config.Config.Key, nil
    })

I get an error which says "Key is invalid or invalid type".我收到一条错误消息,提示“密钥无效或类型无效”。

My config struct looks like this in config.go file -我的配置结构在 config.go 文件中看起来像这样 -

config struct {
 Key string
}

Any suggestions to solve this problem?有什么解决这个问题的建议吗? The token I am passing is a JWT token.我传递的令牌是 JWT 令牌。

config struct {
 Key string
}

Key needs to be a []byte Key必须是[]byte

Other way is to do something like this -另一种方法是做这样的事情 -

token, err := jwt.Parse(getToken, func(token *jwt.Token) (interface{}, error) {
        return []byte(config.Config.Key), nil
    })

The whole idea being that the Parse function returns a slice of bytes.整个想法是 Parse 函数返回一个字节片。

Taking a look at the function signatures in the GoDoc for github.com/dgrijalva/jwt-go we see:查看github.com/dgrijalva/jwt-go 的 GoDoc中的函数签名,我们看到:

func Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

type Keyfunc func(*Token) (interface{}, error)

Keyfunc requires you to return (interface{}, error) . Keyfunc要求您返回(interface{}, error) Given the mysterious interface{} type, you might expect to be fine returning a string ;给定神秘的interface{}类型,您可能希望返回一个string however, a peek under the hood reveals that Parse() tries to Verify() , which attempts the following type assertion with your interface{} value as the key :然而,深入了解Parse()尝试Verify() ,它尝试使用interface{}值作为key进行以下类型断言:

keyBytes, ok := key.([]byte)

That will succeed for []byte types, but will fail for string types.这对于[]byte类型会成功,但对于string类型会失败。 When that fails, the result is the error message you are getting.当失败时,结果是您收到的错误消息。 Read more about type assertions in the Effective Go documentation to learn why it fails. 在 Effective Go 文档中阅读更多关于 类型断言的信息,了解它失败的原因。

Example: https://play.golang.org/p/9KKNFLLQrm示例: https : //play.golang.org/p/9KKNFLLQrm

package main

import "fmt"

func main() {
    var a interface{}
    var b interface{}

    a = []byte("hello")
    b = "hello"

    key, ok := a.([]byte)
    if !ok {
        fmt.Println("a is an invalid type")
    } else {
        fmt.Println(key)
    }

    key, ok = b.([]byte)
    if !ok {
        fmt.Println("b is an invalid type")
    } else {
        fmt.Println(key)
    }
}

[104 101 108 108 111]
b is an invalid type

I am not sure if this can be an issue for someone else.我不确定这对其他人是否有问题。

My problem was I was using Signing Method "SigningMethodES256" but "SigningMethodHS256" or Any with SigningMethodHS* works fine.我的问题是我使用的是签名方法"SigningMethodES256""SigningMethodHS256"或带有SigningMethodHS* Any 工作正常。

If someone knows why this is an issue please answer.如果有人知道为什么这是一个问题,请回答。

This is working for me.这对我有用。

token.SignedString([]byte("mysecretkey")) token.SignedString([]byte("mysecretkey"))

func GenerateJWT(email string, username string) (tokenString string, err error) {

    expirationTime := time.Now().Add(1 * time.Hour)
    claims := &JWTClime{
        Email:    email,
        Username: username,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expirationTime.Unix(),
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, err = token.SignedString([]byte("mysecretkey"))

    return
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM