Home > Software design >  JWT Claims not retained after token signing
JWT Claims not retained after token signing

Time:02-04

I have the following code. I am creating a json web token (using golang-jwt) with custom claims. The issue is that when I sign the token with a key (method = HS256) and then parse the token the claims are getting changed. What mistake I am making.

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

CodePudding user response:

You have to export the userid field (make it start with a capital letter). Unexported fields cannot be JSON encoded.

type MyCustomClaims struct {
    UserID int `json:"userid"`
    jwt.RegisteredClaims
}
  • Related