How does the front-end javascript parse the username in the jwt-token when the front-end and front-end separate projects?

the following is the function used by the backend to generate jwt-token (written by golang), which returns jwt-token to the front end, including username:

// 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:
the front-end javascript receives the jwt-token, how to resolve the username in the jwt-token?

Apr.10,2022
The string generated by

jwt consists of JWT header, payload and signature, and then the string is encoded and processed. If you want to parse it, you first have to decode it.
the key string is generally used for permission verification at the backend, which may be processed with ink at the backend. The frontend needs data, and then an API is encapsulated.
needs username. Just let multiple backends return it directly


you can use the existing javascript library, and randomly find one: https://github.com/auth0/jwt-...


according to the specification.
jwt consists of three parts of data, each of which is encrypted by base64 and connected with . to form an authentication string. Payload is in the second part. In other words, the payload is obtained immediately after the string . is segmented and then decoded by base64.

in the end, the code you posted only deals with the calculation of the third part, and the rest is not reflected.


write an interface to get user data.
jwt exposes as little information as possible. After all, it's just a string encoded by base64.
saving an id is enough

.
Menu