Golang JWT在go-jwt-middleware中无效。

huangapple go评论89阅读模式
英文:

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
}

我没有找到关于validatorissueraudience选项的任何文档,只是按照示例进行操作:

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 &quot;github.com/auth0/go-jwt-middleware/v2&quot;

successfully generate token with &quot;github.com/golang-jwt/jwt/v4&quot; 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:&quot;username&quot;`
Role     string `json:&quot;role&quot;`
Id       string `json:&quot;id&quot;`
Avatar   string `json:&quot;avatar&quot;`
jwt.StandardClaims
}
func (c *Claims) Validate(ctx context.Context) error {
return nil
}
var jwtKey = []byte(&quot;secret&quot;)
func Middleware(h http.Handler) http.Handler {
keyFunc := func(ctx context.Context) (interface{}, error) {
return jwtKey, nil
}
customClaims := func() validator.CustomClaims {
return &amp;Claims{}
}
jwtValidator, err := validator.New(
keyFunc,
validator.HS256,
&quot;issuer&quot;,
[]string{&quot;audience&quot;},
validator.WithCustomClaims(customClaims),
validator.WithAllowedClockSkew(30*time.Second),
)
if err != nil {
log.Fatalf(&quot;Failed to set up the validator: %v&quot;, 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(&quot;Unauthorized&quot;))
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 := &amp;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 &quot;&quot;, 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,
&quot;issuer&quot;, &lt;------------ issuer
[]string{&quot;audience&quot;}, &lt;------------ 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://&lt;issuer-url&gt;/ Who created the token. like token issued by GitHub or LinkedIn and this can be verified by using the OpenID configuration endpoint

huangapple
  • 本文由 发表于 2022年1月22日 11:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/70809804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定