Home > front end >  golang jwt.MapClaims get user ID
golang jwt.MapClaims get user ID

Time:06-21

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:[email protected] 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)
}

CodePudding user response:

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)
    }
  • Related