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

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

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中。实现中可能有一些缺失,也许有人已经实现并愿意分享。

以下是代码:

  1. type Claims struct {
  2. Username string `json:"username"`
  3. Role string `json:"role"`
  4. Id string `json:"id"`
  5. Avatar string `json:"avatar"`
  6. jwt.StandardClaims
  7. }
  8. func (c *Claims) Validate(ctx context.Context) error {
  9. return nil
  10. }
  11. var jwtKey = []byte("secret")
  12. func Middleware(h http.Handler) http.Handler {
  13. keyFunc := func(ctx context.Context) (interface{}, error) {
  14. return jwtKey, nil
  15. }
  16. customClaims := func() validator.CustomClaims {
  17. return &Claims{}
  18. }
  19. jwtValidator, err := validator.New(
  20. keyFunc,
  21. validator.HS256,
  22. "issuer",
  23. []string{"audience"},
  24. validator.WithCustomClaims(customClaims),
  25. validator.WithAllowedClockSkew(30*time.Second),
  26. )
  27. if err != nil {
  28. log.Fatalf("Failed to set up the validator: %v", err)
  29. }
  30. // 设置中间件。
  31. middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
  32. return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  33. _, token, err := ParseToken(r)
  34. if !token.Valid || err != nil {
  35. w.WriteHeader(401)
  36. w.Write([]byte("Unauthorized"))
  37. return
  38. }
  39. h.ServeHTTP(w, r)
  40. }))
  41. }
  42. func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
  43. expirationTime := time.Now().Add(time.Hour * 24).Unix()
  44. claims := &Claims{
  45. Id: id,
  46. Username: username,
  47. Role: role,
  48. Avatar: avatar,
  49. StandardClaims: jwt.StandardClaims{
  50. ExpiresAt: expirationTime,
  51. },
  52. }
  53. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  54. tokenString, err := token.SignedString(jwtKey)
  55. if err != nil {
  56. return "", 0, err
  57. }
  58. return tokenString, expirationTime, nil
  59. }

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

  1. jwtValidator, err := validator.New(
  2. keyFunc,
  3. validator.HS256,
  4. "issuer", <------------ issuer
  5. []string{"audience"}, <------------ audience
  6. validator.WithCustomClaims(customClaims),
  7. validator.WithAllowedClockSkew(30*time.Second),
  8. )
英文:

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:

  1. type Claims struct {
  2. Username string `json:&quot;username&quot;`
  3. Role string `json:&quot;role&quot;`
  4. Id string `json:&quot;id&quot;`
  5. Avatar string `json:&quot;avatar&quot;`
  6. jwt.StandardClaims
  7. }
  8. func (c *Claims) Validate(ctx context.Context) error {
  9. return nil
  10. }
  11. var jwtKey = []byte(&quot;secret&quot;)
  12. func Middleware(h http.Handler) http.Handler {
  13. keyFunc := func(ctx context.Context) (interface{}, error) {
  14. return jwtKey, nil
  15. }
  16. customClaims := func() validator.CustomClaims {
  17. return &amp;Claims{}
  18. }
  19. jwtValidator, err := validator.New(
  20. keyFunc,
  21. validator.HS256,
  22. &quot;issuer&quot;,
  23. []string{&quot;audience&quot;},
  24. validator.WithCustomClaims(customClaims),
  25. validator.WithAllowedClockSkew(30*time.Second),
  26. )
  27. if err != nil {
  28. log.Fatalf(&quot;Failed to set up the validator: %v&quot;, err)
  29. }
  30. // Set up the middleware.
  31. middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
  32. return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  33. _, token, err := ParseToken(r)
  34. if !token.Valid || err != nil {
  35. w.WriteHeader(401)
  36. w.Write([]byte(&quot;Unauthorized&quot;))
  37. return
  38. }
  39. h.ServeHTTP(w, r)
  40. }))
  41. }
  42. func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
  43. expirationTime := time.Now().Add(time.Hour * 24).Unix()
  44. claims := &amp;Claims{
  45. Id: id,
  46. Username: username,
  47. Role: role,
  48. Avatar: avatar,
  49. StandardClaims: jwt.StandardClaims{
  50. ExpiresAt: expirationTime,
  51. },
  52. }
  53. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  54. tokenString, err := token.SignedString(jwtKey)
  55. if err != nil {
  56. return &quot;&quot;, 0, err
  57. }
  58. return tokenString, expirationTime, nil
  59. }

And i don't found any doccumentation for the value for issuer && audience option on validator. just follow the example:

  1. jwtValidator, err := validator.New(
  2. keyFunc,
  3. validator.HS256,
  4. &quot;issuer&quot;, &lt;------------ issuer
  5. []string{&quot;audience&quot;}, &lt;------------ audience
  6. validator.WithCustomClaims(customClaims),
  7. validator.WithAllowedClockSkew(30*time.Second),
  8. )

答案1

得分: 1

发行者:issuerURL,
受众:audience,

受众值是一个字符串,通常是正在访问的资源的基本地址。例如,哪些服务、API、产品应该接受此令牌作为服务的访问令牌。对于 Stackoveflow 的令牌不应该被 Stack exchange 网站接受,即使它们具有相同的发行者,它们的受众也会不同。

发行者值是一个类似于 https://<issuer-url>/ 的字符串,表示谁创建了令牌。例如,由 GitHub 或 LinkedIn 发行的令牌,可以通过使用 OpenID 配置端点进行验证。

英文:
  1. Issuer: issuerURL,
  2. 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:

确定