在Golang中,使用JWT(JSON Web Token)的MapClaims可以获取用户ID。

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

golang jwt.MapClaims get user ID

问题

设置了一个简单的一对多关联,其中用户(user)有多个帖子(posts),要创建一个帖子时需要使用用户ID。因此,如何从JWT声明中获取用户ID呢?

我尝试解析令牌,但只显示了以下内容:

map[email:teste@teste.com exp:1.655701949e+09 username:teste]

以下是代码示例:

tokenString := c.GetHeader("Authorization")
//
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
    return []byte("supersecretkey"), nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
    fmt.Printf("%v", claims)
} else {
    fmt.Println(err)
}
英文:

After setup a simple has many association where user has_many posts to create a post with user ID seems that is necessary parse the jwt Claims to get the userID and place it on Post creation.

So, how to get the user ID from jwt Claims

i tried parse the token but just show up

map[email:teste@teste.com exp:1.655701949e+09 username:teste]



tokenString := c.GetHeader("Authorization")
	//
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
    return []byte("supersecretkey"), nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
    fmt.Printf("%v", claims )
} else {
    fmt.Println(err)
}

答案1

得分: 4

我从一开始就告诉你,当你想要生成JWT时,按照以下方式操作:

token := jwt.New(jwt.SigningMethodHS256)
// 设置声明
// 这是前端可以使用的信息
// 后端也可以解码令牌并获取管理员等信息
claims := token.Claims.(jwt.MapClaims)
claims["username"] = ID
accessTokenExpireTime := time.Now().Add(time.Hour * 48).Unix()
claims["exp"] = accessTokenExpireTime
// 生成编码的令牌并作为响应发送
// 签名字符串应该是保密的(也可以使用生成的UUID)
t, err := token.SignedString([]byte("AccessToken"))

然后,当你想要解码用户名时,按照以下方式操作:

type MyCustomClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

auth := c.Request.Header.Get("Authorization")
if auth == "" {
	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Authorization Header Not Found"})
	return
}
splitToken := strings.Split(auth, "Bearer ")
auth = splitToken[1]

token, err := jwt.ParseWithClaims(auth, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
	return []byte("AccessToken"), nil
})

if err != nil {
	c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Token is wrong or Expire"})
	return
}

if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
	log.Printf("%v %v", claims.Username, claims.StandardClaims.ExpiresAt)
}
英文:

I told u from first, when u wanna generate JWT
do like below:

token := jwt.New(jwt.SigningMethodHS256)
// Set claims
// This is the information which frontend can use
// The backend can also decode the token and get admin etc.
claims := token.Claims.(jwt.MapClaims)
claims["username"] = ID
accessTokenExpireTime := time.Now().Add(time.Hour * 48).Unix()
claims["exp"] = accessTokenExpireTime
// Generate encoded token and send it as response.
// The signing string should be secret (a generated UUID works too)
t, err := token.SignedString([]byte("AccessToken"))

And then when u wanna to decode username do like below:

type MyCustomClaims struct {
		Username string `json:"username"`
		jwt.StandardClaims
	}

	auth := c.Request.Header.Get("Authorization")
	if auth == "" {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Authorization Header Not Found"})
		return
	}
	splitToken := strings.Split(auth, "Bearer ")
	auth = splitToken[1]

	token, err := jwt.ParseWithClaims(auth, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("AccessToken"), nil
	})

	if err != nil {
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Token is wrong or Expire"})
		return
	}


	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		log.Printf("%v %v", claims.Username, claims.StandardClaims.ExpiresAt)
	}

huangapple
  • 本文由 发表于 2022年6月20日 12:30:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/72682230.html
匿名

发表评论

匿名网友

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

确定