🐛 Fix on reading jwt claims

This commit is contained in:
LittleSheep 2024-10-30 23:59:04 +08:00
parent f9b6cd2e20
commit 3f6ea11d22
4 changed files with 12 additions and 4 deletions

View File

@ -31,6 +31,6 @@ func tokenRead(in string) (*sec.JwtClaims, error) {
return nil, nil return nil, nil
} }
claims, err := sec.ReadJwt[sec.JwtClaims](JReader, in) claims, err := sec.ReadJwt[*sec.JwtClaims](JReader, in, &sec.JwtClaims{})
return &claims, err return claims, err
} }

View File

@ -9,6 +9,7 @@ import (
"git.solsynth.dev/hypernet/nexus/pkg/proto" "git.solsynth.dev/hypernet/nexus/pkg/proto"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log" "github.com/rs/zerolog/log"
"strconv"
"time" "time"
) )
@ -26,8 +27,12 @@ func userinfoFetch(c *fiber.Ctx) error {
} else { } else {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() 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{ resp, err := proto.NewAuthServiceClient(conn).Authenticate(ctx, &proto.AuthRequest{
SessionId: uint64(claims.Session), SessionId: uint64(sed),
}) })
if err != nil { if err != nil {
return fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("unable to load userinfo: %v", err)) return fiber.NewError(fiber.StatusUnauthorized, fmt.Sprintf("unable to load userinfo: %v", err))

View File

@ -9,7 +9,7 @@ type JwtClaims struct {
jwt.RegisteredClaims jwt.RegisteredClaims
// Nexus Standard // Nexus Standard
Session int `json:"sed"` Session string `json:"sed"`
CacheTTL time.Duration `json:"ttl,omitempty"` CacheTTL time.Duration `json:"ttl,omitempty"`
// OIDC Standard // OIDC Standard

View File

@ -39,6 +39,9 @@ func NewJwtReader(fp string) (*JwtReader, error) {
}, nil }, 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) { 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) { token, err := jwt.ParseWithClaims(in, out, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {