undefinedfix
Sign in

How can front-end JavaScript parse the user name in JWT token?

nasa edited in Fri, 10 Jun 2022

The following is the function used by the back end to generate the JWT token (written by golang). It will return the JWT token to the front end, which contains the user name:

// Sign signs the context with the specified secret.
func Sign(ctx *gin.Context, c Context, secret string) (tokenString string, err error) {
    // Load the jwt secret from the Gin config if the secret isn't specified.
    if secret == "" {
        secret = viper.GetString("jwt_secret")
    }
    // The token content.
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "id":       c.ID,
        "username": c.Username,
        "nbf":      time.Now().Unix(),
        "iat":      time.Now().Unix(),
    })
    // Sign the token with the specified secret.
    tokenString, err = token.SignedString([]byte(secret))

    return
}

Question: when the front-end JavaScript receives the JWT token, how can it parse the user name in the JWT token?

4 Replies
Antonino
commented on Fri, 10 Jun 2022

The string generated by JWT is composed of JWT header, payload and signature. Then it is encoded and processed. If you want to parse it, you have to decode it first. The key string is generally used for back-end permission verification. The back-end may also add ink. The front-end needs data, and then encapsulates an interface. Need a user name, directly let multiple back-end return it

Whitemetalco
commented on Fri, 10 Jun 2022

You can use the existing JavaScript library to find any one: https://github.com/auth0/jwt-...

obidano
commented on Fri, 10 Jun 2022

According to the specification. JWT consists of three parts of data, each part is encrypted by Base64 and connected to form an authentication string. Payload is in the second part. That is to say, through the string. Segmentation and then Base64 decoding, immediately get the payload.

Finally, the code you posted only involves the calculation of the third part, and the rest is not reflected.

user617544
commented on Fri, 10 Jun 2022

Write an interface to get user data. The less information exposed by JWT, the better. After all, it's just a Base64 encoded string. It's enough to save an ID

lock This question has been locked and the reply function has been disabled.