[英]How to verify a JSON Web Token with the jwt-go library?
I am using the jwt-go library in golang, and using the HS512 algorithm for signing the token.我在 golang 中使用 jwt-go 库,并使用HS512算法对令牌进行签名。 I want to make sure the token is valid and the example in the docs is like this:
我想确保令牌有效并且文档中的示例是这样的:
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
return myLookupKey(token.Header["kid"])
})
if err == nil && token.Valid {
fmt.Println("Your token is valid. I like your style.")
} else {
fmt.Println("This token is terrible! I cannot accept this.")
}
I understand that myToken
is the string token and the keyFunc
gets passed the parsed token, but I don't understand what myLookupKey
function is supposed to do?, and token.Header
doesn't have a kid
value when i print it to console and even thought the token has all the data I put in it, token.Valid
is always false.据我所知,
myToken
是字符串令牌和keyFunc
被传递解析道理,但我不明白什么myLookupKey
功能是应该做的?和token.Header
没有一个kid
值当我打印到控制台,甚至认为令牌包含我放入的所有数据, token.Valid
始终为 false。 Is this a bug?这是一个错误吗? How do I verify the token is valid?
如何验证令牌是否有效?
The keyFunc
is supposed to return the private key that the library should use to verify the token's signature. keyFunc
应该返回库应该用来验证令牌签名的私钥。 How you obtain this key is entirely up to you.您如何获得此密钥完全取决于您。
The example from the documentation shows a non-standard (not defined in RFC 7519 ) additional feature that is offered by the jwt-go library.文档中的示例显示了 jwt-go 库提供的非标准(未在RFC 7519 中定义)附加功能。 Using a
kid
field in the header (short for key ID ), clients can specify with which key the token was signed.使用标头中的
kid
字段(密钥 ID 的缩写),客户端可以指定令牌使用哪个密钥进行签名。 On verification, you can then use the key ID to look up one of (possible several) known keys (how and if you implement this key lookup is up to you).在验证时,您可以使用密钥 ID 查找(可能是多个)已知密钥之一(如何以及是否实施此密钥查找取决于您)。
If you do not want to use this feature, just don't.如果您不想使用此功能,请不要使用。 Simply return a static byte stream from the
keyFunc
without inspecting the token headers:只需从
keyFunc
返回一个静态字节流,而无需检查令牌标头:
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
key, err := ioutil.ReadFile("your-private-key.pem")
if err != nil {
return nil, errors.New("private key could not be loaded")
}
return key, nil
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.