doufu9947 2016-01-03 15:41
浏览 38
已采纳

如何使用jwt-go库验证JSON Web令牌?

I am using the jwt-go library in golang, and using the HS512 algorithm for signing the token. 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. Is this a bug? How do I verify the token is valid?

  • 写回答

1条回答 默认 最新

  • dongsonghen9931 2016-01-03 16:20
    关注

    The keyFunc is supposed to return the private key that the library should use to verify the token's signature. 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. Using a kid field in the header (short for key ID), clients can specify with which key the token was signed. 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).

    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:

    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
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效