From 3f6ea11d2297eb68c870c8cf2f87672705cc9c3b Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Wed, 30 Oct 2024 23:59:04 +0800 Subject: [PATCH] :bug: Fix on reading jwt claims --- pkg/internal/auth/token.go | 4 ++-- pkg/internal/auth/userinfo.go | 7 ++++++- pkg/nex/sec/jwt_claims.go | 2 +- pkg/nex/sec/jwt_reader.go | 3 +++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/pkg/internal/auth/token.go b/pkg/internal/auth/token.go index d9867c0..22bdfb7 100644 --- a/pkg/internal/auth/token.go +++ b/pkg/internal/auth/token.go @@ -31,6 +31,6 @@ func tokenRead(in string) (*sec.JwtClaims, error) { return nil, nil } - claims, err := sec.ReadJwt[sec.JwtClaims](JReader, in) - return &claims, err + claims, err := sec.ReadJwt[*sec.JwtClaims](JReader, in, &sec.JwtClaims{}) + return claims, err } diff --git a/pkg/internal/auth/userinfo.go b/pkg/internal/auth/userinfo.go index 98fe8b8..2c8a7fe 100644 --- a/pkg/internal/auth/userinfo.go +++ b/pkg/internal/auth/userinfo.go @@ -9,6 +9,7 @@ import ( "git.solsynth.dev/hypernet/nexus/pkg/proto" "github.com/gofiber/fiber/v2" "github.com/rs/zerolog/log" + "strconv" "time" ) @@ -26,8 +27,12 @@ func userinfoFetch(c *fiber.Ctx) error { } else { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() + sed, err := strconv.Atoi(claims.Session) + if err != nil { + return fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("invalid token payload")) + } resp, err := proto.NewAuthServiceClient(conn).Authenticate(ctx, &proto.AuthRequest{ - SessionId: uint64(claims.Session), + SessionId: uint64(sed), }) if err != nil { return fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("unable to load userinfo: %v", err)) diff --git a/pkg/nex/sec/jwt_claims.go b/pkg/nex/sec/jwt_claims.go index e0dcb45..baeb611 100644 --- a/pkg/nex/sec/jwt_claims.go +++ b/pkg/nex/sec/jwt_claims.go @@ -9,7 +9,7 @@ type JwtClaims struct { jwt.RegisteredClaims // Nexus Standard - Session int `json:"sed"` + Session string `json:"sed"` CacheTTL time.Duration `json:"ttl,omitempty"` // OIDC Standard diff --git a/pkg/nex/sec/jwt_reader.go b/pkg/nex/sec/jwt_reader.go index 89b1a96..9963bfe 100644 --- a/pkg/nex/sec/jwt_reader.go +++ b/pkg/nex/sec/jwt_reader.go @@ -39,6 +39,9 @@ func NewJwtReader(fp string) (*JwtReader, error) { }, nil } +// ReadJwt is the helper method to help me validate and parse jwt. +// To use it, pass the initialized jwt reader which contains public key. +// And pass the token string, and a pointer struct (you must initialize it, which it cannot be nil) of your claims func ReadJwt[T jwt.Claims](v *JwtReader, in string, out T) (T, error) { token, err := jwt.ParseWithClaims(in, out, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {