Home > Backend Development > Golang > JWT claims not preserved after token signing

JWT claims not preserved after token signing

王林
Release: 2024-02-14 09:40:09
forward
651 people have browsed it

令牌签名后 JWT 声明不保留

php editor Banana will introduce an important concept in JWT (JSON Web Token) in this article: token signature. JWT is a security standard for passing information between web applications. In JWT, token signing is a mechanism to protect the integrity and authenticity of the token. Once the token is signed, any tampering or forgery of the token will be immediately detected. However, sometimes we may need to not preserve the signature of the JWT claim in certain situations, and this article will explain in detail how to achieve this requirement.

Question content

I have the following code. I'm using custom claims to create a json web token (using golang-jwt). The problem is that when I sign the token using the key (method = hs256) and then parse the token, the claims change. What mistake did I make.

Code:

package main

import (
    "fmt"
    "time"

    "github.com/golang-jwt/jwt/v4"
)

type mycustomclaims struct {
    userid int
    jwt.registeredclaims
}

func (app *config) generatejwt(userid int) {

    //code to generate jwt
    jt := jwt.newwithclaims(jwt.signingmethodhs256, mycustomclaims{
        userid,
        jwt.registeredclaims{
            expiresat: jwt.newnumericdate(time.now().add(3 * time.hour)),
            issuedat:  jwt.newnumericdate(time.now()),
        },
    })

    fmt.println("what was put", jt.claims.(mycustomclaims).userid)
    token, _ := jt.signedstring(app.secret)

    //code to check whether claims are retained
    parsed_token, _ := jwt.parsewithclaims(token, &mycustomclaims{}, func(t *jwt.token) (interface{}, error) {
        return app.secret, nil
    })

    fmt.println("what was parsed", parsed_token.claims.(*mycustomclaims).userid)

}

Copy after login

Output

What was put 8
What was parsed 0
Copy after login

Workaround

You must export the user id field (make it start with a capital letter). Unexported fields cannot be json encoded.

type MyCustomClaims struct {
    UserID int `json:"userid"`
    jwt.RegisteredClaims
}
Copy after login

The above is the detailed content of JWT claims not preserved after token signing. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template