Skip to content

Commit 7b1c1c0

Browse files
authored
Merge commit from fork
* Initial draft of adding text to ParseWithClaims * Adjusted example and referring to the example in Parse functions * Backporting logic from v5 * Added a test
1 parent 9358574 commit 7b1c1c0

File tree

3 files changed

+36
-22
lines changed

3 files changed

+36
-22
lines changed

example_test.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ func ExampleParseWithClaims_customClaimsType() {
9393
// Output: bar test
9494
}
9595

96-
// An example of parsing the error types using bitfield checks
96+
// An example of parsing the error types using [errors.Is].
9797
func ExampleParse_errorChecking() {
9898
// Token from another example. This token is expired
9999
var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
@@ -106,6 +106,10 @@ func ExampleParse_errorChecking() {
106106
fmt.Println("You look nice today")
107107
} else if errors.Is(err, jwt.ErrTokenMalformed) {
108108
fmt.Println("That's not even a token")
109+
} else if errors.Is(err, jwt.ErrTokenUnverifiable) {
110+
fmt.Println("We could not verify this token")
111+
} else if errors.Is(err, jwt.ErrTokenSignatureInvalid) {
112+
fmt.Println("This token has an invalid signature")
109113
} else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) {
110114
// Token is either expired or not active yet
111115
fmt.Println("Timing is everything")

parser.go

+20-21
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,21 @@ func NewParser(options ...ParserOption) *Parser {
3636
return p
3737
}
3838

39-
// Parse parses, validates, verifies the signature and returns the parsed token.
40-
// keyFunc will receive the parsed token and should return the key for validating.
39+
// Parse parses, validates, verifies the signature and returns the parsed token. keyFunc will
40+
// receive the parsed token and should return the key for validating.
4141
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
4242
return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
4343
}
4444

45-
// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims
46-
// interface. This provides default values which can be overridden and allows a caller to use their own type, rather
47-
// than the default MapClaims implementation of Claims.
45+
// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object
46+
// implementing the Claims interface. This provides default values which can be overridden and
47+
// allows a caller to use their own type, rather than the default MapClaims implementation of
48+
// Claims.
4849
//
49-
// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
50-
// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
51-
// proper memory for it before passing in the overall claims, otherwise you might run into a panic.
50+
// Note: If you provide a custom claim implementation that embeds one of the standard claims (such
51+
// as RegisteredClaims), make sure that a) you either embed a non-pointer version of the claims or
52+
// b) if you are using a pointer, allocate the proper memory for it before passing in the overall
53+
// claims, otherwise you might run into a panic.
5254
func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
5355
token, parts, err := p.ParseUnverified(tokenString, claims)
5456
if err != nil {
@@ -85,35 +87,32 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf
8587
return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
8688
}
8789

90+
// Perform validation
91+
token.Signature = parts[2]
92+
if err := token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
93+
return token, &ValidationError{Inner: err, Errors: ValidationErrorSignatureInvalid}
94+
}
95+
8896
vErr := &ValidationError{}
8997

9098
// Validate Claims
9199
if !p.SkipClaimsValidation {
92100
if err := token.Claims.Valid(); err != nil {
93-
94101
// If the Claims Valid returned an error, check if it is a validation error,
95102
// If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
96103
if e, ok := err.(*ValidationError); !ok {
97104
vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
98105
} else {
99106
vErr = e
100107
}
108+
return token, vErr
101109
}
102110
}
103111

104-
// Perform validation
105-
token.Signature = parts[2]
106-
if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
107-
vErr.Inner = err
108-
vErr.Errors |= ValidationErrorSignatureInvalid
109-
}
110-
111-
if vErr.valid() {
112-
token.Valid = true
113-
return token, nil
114-
}
112+
// No errors so far, token is valid.
113+
token.Valid = true
115114

116-
return token, vErr
115+
return token, nil
117116
}
118117

119118
// ParseUnverified parses the token but doesn't validate the signature.

parser_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@ var jwtTestData = []struct {
111111
nil,
112112
jwt.SigningMethodRS256,
113113
},
114+
{
115+
"basic invalid and expired",
116+
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIiLCJleHAiOjEyMzR9.IbFvatLIJ2Z7B_MAaeIaRZsRSQF1CDzmAE0osHII3WfRTbPavonrDXz-p2Ap_oh9LT2lyohL_jCLoVcpTyu7K3Rt-hdgxZ1_r1StwM1we0SqW2BFFeXCzyS9SLf2YTaVR35lVvfwwlCpPBgOw1SBbczm9m6yPgA9Afsvw_lG_GU2civvG0UzHXxbzWWvJoflGokJDuoHQiku2bfxReyNsoUGcLjx5tfkY7cPihM3CffPpRFYCVjv_abHYelZWpVjdGULQyJDInGYqO8oANqNTtjui7aqxBpcFCUBwVVgktM4Q6Dvj-o5LrdPyJSEl0b_R2JstFE5CbEZGN5anN1yHa",
117+
defaultKeyFunc,
118+
jwt.MapClaims{"foo": "bar", "exp": 1234.0},
119+
false,
120+
jwt.ValidationErrorSignatureInvalid,
121+
[]error{jwt.ErrTokenSignatureInvalid, rsa.ErrVerification},
122+
nil,
123+
jwt.SigningMethodRS256,
124+
},
114125
{
115126
"basic nokeyfunc",
116127
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",

0 commit comments

Comments
 (0)