英文:
Golang JWT is invalid with go-jwt-middleware
问题
在使用新版本的"github.com/auth0/go-jwt-middleware/v2"
时,出现了JWT is invalid
的错误。
我成功使用了"github.com/golang-jwt/jwt/v4"
插件生成了令牌,并尝试在请求中使用它,但在中间件中被拒绝了,我猜测问题出在go-jwt-middleware
中。实现中可能有一些缺失,也许有人已经实现并愿意分享。
以下是代码:
type Claims struct {
Username string `json:"username"`
Role string `json:"role"`
Id string `json:"id"`
Avatar string `json:"avatar"`
jwt.StandardClaims
}
func (c *Claims) Validate(ctx context.Context) error {
return nil
}
var jwtKey = []byte("secret")
func Middleware(h http.Handler) http.Handler {
keyFunc := func(ctx context.Context) (interface{}, error) {
return jwtKey, nil
}
customClaims := func() validator.CustomClaims {
return &Claims{}
}
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer",
[]string{"audience"},
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
if err != nil {
log.Fatalf("Failed to set up the validator: %v", err)
}
// 设置中间件。
middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, token, err := ParseToken(r)
if !token.Valid || err != nil {
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
return
}
h.ServeHTTP(w, r)
}))
}
func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
expirationTime := time.Now().Add(time.Hour * 24).Unix()
claims := &Claims{
Id: id,
Username: username,
Role: role,
Avatar: avatar,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", 0, err
}
return tokenString, expirationTime, nil
}
我没有找到关于validator
中issuer
和audience
选项的任何文档,只是按照示例进行操作:
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer", <------------ issuer
[]string{"audience"}, <------------ audience
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
英文:
Got JWT is invalid
with new version of "github.com/auth0/go-jwt-middleware/v2"
successfully generate token with "github.com/golang-jwt/jwt/v4"
plugin, and try to use it on request but rejected on middleware, i guess the issues in go-jwt-middleware
. there is some missing with implementation, maybe anyone has already implement and want to share please
Here is the code:
type Claims struct {
Username string `json:"username"`
Role string `json:"role"`
Id string `json:"id"`
Avatar string `json:"avatar"`
jwt.StandardClaims
}
func (c *Claims) Validate(ctx context.Context) error {
return nil
}
var jwtKey = []byte("secret")
func Middleware(h http.Handler) http.Handler {
keyFunc := func(ctx context.Context) (interface{}, error) {
return jwtKey, nil
}
customClaims := func() validator.CustomClaims {
return &Claims{}
}
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer",
[]string{"audience"},
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
if err != nil {
log.Fatalf("Failed to set up the validator: %v", err)
}
// Set up the middleware.
middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, token, err := ParseToken(r)
if !token.Valid || err != nil {
w.WriteHeader(401)
w.Write([]byte("Unauthorized"))
return
}
h.ServeHTTP(w, r)
}))
}
func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
expirationTime := time.Now().Add(time.Hour * 24).Unix()
claims := &Claims{
Id: id,
Username: username,
Role: role,
Avatar: avatar,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return "", 0, err
}
return tokenString, expirationTime, nil
}
And i don't found any doccumentation for the value for issuer
&& audience
option on validator. just follow the example:
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
"issuer", <------------ issuer
[]string{"audience"}, <------------ audience
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
答案1
得分: 1
发行者:issuerURL,
受众:audience,
受众值是一个字符串,通常是正在访问的资源的基本地址。例如,哪些服务、API、产品应该接受此令牌作为服务的访问令牌。对于 Stackoveflow 的令牌不应该被 Stack exchange 网站接受,即使它们具有相同的发行者,它们的受众也会不同。
发行者值是一个类似于 https://<issuer-url>/
的字符串,表示谁创建了令牌。例如,由 GitHub 或 LinkedIn 发行的令牌,可以通过使用 OpenID 配置端点进行验证。
英文:
Issuer: issuerURL,
Audience: audience,
The audience value is a string -- typically, the base address of the resource being accessed. for example which services, APIs, products should accept this token as an access token for the service. A token valid for Stackoveflow should not be accepted for the Stack exchange website, even if both of them have the same issuer, they’ll have different audiences.
Issuer value is a string like this https://<issuer-url>/
Who created the token. like token issued by GitHub or LinkedIn and this can be verified by using the OpenID configuration endpoint
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论