英文:
JWT Claims not retained after token signing
问题
我有以下代码。我正在使用golang-jwt创建一个带有自定义声明的JSON Web Token。问题是,当我使用密钥(方法为HS256)对令牌进行签名,然后解析令牌时,声明会发生变化。我犯了什么错误。
代码:
package main
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v4"
)
type MyCustomClaims struct {
userid int
jwt.RegisteredClaims
}
func (app *Config) generateJWT(userid int) {
//生成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("放入的内容", jt.Claims.(MyCustomClaims).userid)
token, _ := jt.SignedString(app.secret)
//检查声明是否保留的代码
parsed_token, _ := jwt.ParseWithClaims(token, &MyCustomClaims{}, func(t *jwt.Token) (interface{}, error) {
return app.secret, nil
})
fmt.Println("解析的内容", parsed_token.Claims.(*MyCustomClaims).userid)
}
输出
放入的内容 8
解析的内容 0
英文:
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
答案1
得分: 2
你必须导出userid字段(使其以大写字母开头)。未导出的字段无法进行JSON编码。
type MyCustomClaims struct {
UserID int `json:"userid"`
jwt.RegisteredClaims
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论