Creating a token using a custom claims type

suggest change

Embed jwt.RegisteredClaims in a custom type to encode and validate registered claims alongside application-specific claims.

tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"

type MyCustomClaims struct {
    Foo string `json:"foo"`
    jwt.RegisteredClaims
}

// The sample token is expired. Override the clock only to make this example
// deterministic; production code should use the real clock.
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
    return []byte("AllYourBase"), nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}), jwt.WithTimeFunc(func() time.Time {
    return time.Unix(0, 0)
}))

if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
    fmt.Printf("%v %v", claims.Foo, claims.ExpiresAt.Unix())
} else {
    fmt.Println(err)
}
bar 15000

In production, use the real clock. WithTimeFunc is appropriate here only because the fixed sample token expired long ago.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents