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

JWT claims not preserved after token signing

王林
王林forward
2024-02-14 09:40:09626browse

令牌签名后 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)

}

Output

What was put 8
What was parsed 0

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
}

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete