我正在尝试将令牌传递给" Parse(令牌字符串,keyFunc Keyfunc)" GO程序集中定义的GO例程(http://godoc.org/github.com/dgrijalva/jwt-go)用于JWT令牌解析/验证。
当我将令牌传递给此函数时 -
token, err := jwt.Parse(getToken, func(token *jwt.Token) (interface{}, error) {
return config.Config.Key, nil
})
我收到错误,上面写着"密钥无效或类型无效"。
我的config结构在config.go文件中看起来像这样 -
config struct {
Key string
}
有什么建议可以解决这个问题吗?我传递的令牌是JWT令牌。
答案 0 :(得分:7)
config struct {
Key string
}
Key
必须是[]byte
答案 1 :(得分:1)
其他方式是做这样的事情 -
token, err := jwt.Parse(getToken, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.Key), nil
})
整个想法是Parse函数返回一个字节片段。
答案 2 :(得分:0)
看一下我们看到的GoDoc for github.com/dgrijalva/jwt-go中的功能签名:
func Parse(tokenString string, keyFunc Keyfunc) (*Token, error)
type Keyfunc func(*Token) (interface{}, error)
Keyfunc
要求您返回(interface{}, error)
。鉴于神秘的interface{}
类型,您可能会期望返回string
;然而,在引擎盖下看到Parse()
尝试Verify()
,尝试使用interface{}
值作为key
的以下类型断言:
keyBytes, ok := key.([]byte)
[]byte
类型会成功,但string
类型会失败。如果失败,结果就是您收到的错误消息。阅读有关type assertions in the Effective Go documentation的更多信息,了解它失败的原因。
示例: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