From 2a0b2d4af7b97dd8c2c6f3cfbf3cd067bce7b6cb Mon Sep 17 00:00:00 2001 From: Jack Clarke Date: Mon, 2 Dec 2024 16:28:47 +0000 Subject: [PATCH] change error handling to match new jwtgo package validation flow --- jwk/rs256.go | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/jwk/rs256.go b/jwk/rs256.go index 230b30d..152d54a 100644 --- a/jwk/rs256.go +++ b/jwk/rs256.go @@ -23,24 +23,34 @@ import ( // parseClaims parses a token for claims, and validates using a signature key. func parseClaims(tokenString string, pubKey *rsa.PublicKey, validate bool, claims jwtgo.Claims) (*jwtgo.Token, error) { - var parser jwtgo.Parser + var parser *jwtgo.Parser alg := jwtgo.SigningMethodRS256.Name - parser = jwtgo.Parser{ValidMethods: []string{alg}} + if validate { + parser = jwtgo.NewParser(jwtgo.WithValidMethods([]string{alg})) + } else { + parser = jwtgo.NewParser(jwtgo.WithValidMethods([]string{alg}), jwtgo.WithoutClaimsValidation()) + } + token, err := parser.ParseWithClaims(tokenString, claims, func(token *jwtgo.Token) (verifykey interface{}, err error) { return pubKey, nil }) - // NOTE: we check err futher down due to how jwt-go handles sig verification errors + + if err != nil { + if errors.Is(err, jwtgo.ErrTokenMalformed) { + return nil, fmt.Errorf("malformed token: %w", err) + } + if errors.Is(err, jwtgo.ErrTokenSignatureInvalid) { + return nil, fmt.Errorf("invalid signature: %w", err) + } + if errors.Is(err, jwtgo.ErrTokenExpired) { + return nil, fmt.Errorf("expired token: %w", err) + } + return nil, fmt.Errorf("token validation failed: %w", err) + } + if token == nil { return nil, fmt.Errorf("nil jwk token") } - validErr := token.Claims.Valid() - if validate && validErr != nil { - return nil, fmt.Errorf("jwk token claim invalid: %v", validErr) - } - // NOTE: check if there was a parse error from above - if err != nil { - return nil, err - } if !token.Valid { return nil, fmt.Errorf("invalid jwk token") }