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

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

Using jwt-go Library - Key is invalid or invalid type

问题

我正在尝试将一个令牌传递给这个GO库中定义的"Parse(token String, keyFunc Keyfunc)"函数,用于JWT令牌的解析/验证。

当我将令牌传递给这个函数时 -

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

我收到一个错误,错误信息是"Key is invalid or invalid type"。

我的config结构在config.go文件中看起来像这样 -

config struct {
    Key string
}

有什么建议来解决这个问题吗?我传递的令牌是一个JWT令牌。

英文:

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.

When I pass the token to this 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 struct {
    Key string
}

Any suggestions to solve this problem? The token I am passing is a JWT token.

答案1

得分: 19

config 结构体 {
Key 字符串
}

Key 需要是 []byte 类型的。

英文:
config struct {
    Key string
}

Key needs to be a []byte

答案2

得分: 14

我不确定这是否会成为其他人的问题。

我的问题是我使用了签名方法"SigningMethodES256",但是"SigningMethodHS256"或任何带有SigningMethodHS*的方法都可以正常工作。

如果有人知道为什么会出现这个问题,请回答。

英文:

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.

If someone knows why this is an issue please answer.

答案3

得分: 6

另一种方法是这样做:

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

整个思路是Parse函数返回一个字节切片。

英文:

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.

答案4

得分: 1

github.com/dgrijalva/jwt-go的GoDoc中查看函数签名,我们可以看到:

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类型会失败。当失败时,你会得到你所看到的错误消息。阅读更多关于Effective Go文档中的类型断言,了解为什么会失败。

示例: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是一个无效的类型")
    } else {
        fmt.Println(key)
    }

    key, ok = b.([]byte)
    if !ok {
        fmt.Println("b是一个无效的类型")
    } else {
        fmt.Println(key)
    }
}

[104 101 108 108 111]
b是一个无效的类型
英文:

Taking a look at the function signatures in the GoDoc for github.com/dgrijalva/jwt-go we see:

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

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

Keyfunc requires you to return (interface{}, error). Given the mysterious interface{} type, you might expect to be fine returning a 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:

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

That will succeed for []byte types, but will fail for string types. 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.

Example: 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

答案5

得分: 1

这是对我有效的。

> 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
}
英文:

This is working for me.

> 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
}

huangapple
  • 本文由 发表于 2015年1月29日 07:28:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/28204385.html
匿名

发表评论

匿名网友

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

确定