在 Golang 中解码 JWT 令牌 [英] decoding JWT token in Golang

查看:34
本文介绍了在 Golang 中解码 JWT 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个 Golang 应用程序.我从客户端收到一个 JWT 令牌,在 Go 中我需要解码该令牌并获取信息:用户、名称等.我正在检查可用的库处理 JWT 令牌,我来到 https://github.com/dgrijalva/jwt-go,但我不知道如何简单地制作我需要的东西.

I am currently working on a Golang application.I receive a JWT token from the client side and, in Go I need to decode that token and get the information: user, name, etc. I was checking the libraries that are available to handle JWT tokens and I came down to https://github.com/dgrijalva/jwt-go, but I don't see how to simply make what I need.

我有令牌,我需要将信息解码为地图或至少一个 json.我在哪里可以找到如何操作的指南?谢谢!

I have the token and I need to decode the info into a map or at least a json. Where can I find a guide of how to do it? Thank you!

推荐答案

函数 jwt.ParseWithClaims 接受 jwt.Claims 的接口作为第二个参数.除了基于结构的自定义声明外,该包还提供基于 map 的声明,即 jwt.MapClaims.因此,您可以简单地将令牌解码为 MapClaims,例如

Function jwt.ParseWithClaims accept an interface of jwt.Claims as the second argument. Besides struct-based custom claims, the package also provides map-based claims, i.e. jwt.MapClaims. So, you can simply decode the token into a MapClaims, e.g.

tokenString := "<YOUR TOKEN STRING>"    
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
    return []byte("<YOUR VERIFICATION KEY>"), nil
})
// ... error handling

// do something with decoded claims
for key, val := range claims {
    fmt.Printf("Key: %v, value: %v
", key, val)
}

这篇关于在 Golang 中解码 JWT 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆