golang jwt.MapClaims 获取用户ID

设置后,一个简单的有很多关联,其中用户 has_many posts 创建一个带有用户 ID 的帖子似乎有必要解析 jwt Claims 以获取 userID 并将其放置在帖子创建中。


那么,如何从 jwt Claims 获取用户 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)

}


一只甜甜圈
浏览 286回答 1
1回答

不负相思意

我从一开始就告诉过你,当你想生成 JWT 时,请执行以下操作: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"] = IDaccessTokenExpireTime := 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"))然后当你想解码用户名时,请执行以下操作: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)    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go