在Golang中解码JWT令牌

在Golang中解码JWT令牌

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

问题描述

我目前正在使用Golang应用程序.我从客户端收到JWT令牌,在Go中,我需要对该令牌进行解码并获取以下信息:用户,名称等.我正在检查可用的库来处理JWT令牌,而我来到了一个,但是我不知道如何简单地做我需要的.我有令牌,我需要将信息解码为地图或至少为json.在哪里可以找到如何做的指南?谢谢!

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 this one, but I don't see how to simply make what I need.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\n", key, val)
}

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

07-31 18:32