From 074b95d1752491cc83fb0447e3f2ef820d9d865e Mon Sep 17 00:00:00 2001 From: Ke Chen Date: Mon, 1 Apr 2024 15:33:07 +0800 Subject: [PATCH] fix: use jwt.NumericDate instead time.Time for jwt parsing --- common/user.go | 13 +++++++------ go.mod | 1 + go.sum | 2 ++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/common/user.go b/common/user.go index eccae9a..079aaf7 100644 --- a/common/user.go +++ b/common/user.go @@ -4,17 +4,18 @@ import ( "encoding/base64" "encoding/json" "github.com/gofiber/fiber/v2" + "github.com/golang-jwt/jwt/v5" "log/slog" "strings" "time" ) type UserClaims struct { - ID int `json:"id,omitempty"` - UserID int `json:"user_id,omitempty"` - UID int `json:"uid,omitempty"` - IsAdmin bool `json:"is_admin"` - ExpiresAt *time.Time `json:"exp,omitempty"` + ID int `json:"id,omitempty"` + UserID int `json:"user_id,omitempty"` + UID int `json:"uid,omitempty"` + IsAdmin bool `json:"is_admin"` + ExpiresAt *jwt.NumericDate `json:"exp,omitempty"` } type User struct { @@ -55,7 +56,7 @@ func ParseJWTToken(token string, user any) error { // jwt encoding uses url safe base64 encoding, so RawURLEncoding should be used instead of RawStdEncoding payloadBytes, err := base64.RawURLEncoding.DecodeString(payloadString) // the middle one is payload if err != nil { - slog.Error("jwt parse error", "err", err, "payload_string", payloadString) + slog.Error("jwt parse error", "err", err, "payload_string", payloadString, "payload_bytes", string(payloadBytes)) return ErrInvalidJWTToken } diff --git a/go.mod b/go.mod index 16bc981..cf0ecf2 100644 --- a/go.mod +++ b/go.mod @@ -42,6 +42,7 @@ require ( github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect + github.com/golang-jwt/jwt/v5 v5.2.1 // indirect github.com/golang/mock v1.6.0 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.5.0 // indirect diff --git a/go.sum b/go.sum index 45f6b80..8a41540 100644 --- a/go.sum +++ b/go.sum @@ -134,6 +134,8 @@ github.com/gofiber/fiber/v2 v2.52.4/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtg github.com/gofiber/swagger v1.0.0 h1:BzUzDS9ZT6fDUa692kxmfOjc1DZiloLiPK/W5z1H1tc= github.com/gofiber/swagger v1.0.0/go.mod h1:QrYNF1Yrc7ggGK6ATsJ6yfH/8Zi5bu9lA7wB8TmCecg= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=