Created
November 1, 2016 19:10
-
-
Save zgiber/5e837d3e3c6ddbf867a1bca072823f61 to your computer and use it in GitHub Desktop.
Reproduce validate issues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func TestValidate(t *testing.T) { | |
validRawToken := jwtBytes(testJWT()) | |
expiredToken := testJWT() | |
expiredToken.Claims().SetExpiration(time.Now().Add(-24 * time.Hour)) | |
expiredRawToken := jwtBytes(expiredToken) | |
badRawToken := []byte("You know I'm bad, I'm bad - you know it") | |
testCases := []struct { | |
name string | |
rawJWT []byte | |
expectedError error | |
}{ | |
{"valid JWT", validRawToken, nil}, | |
{"expired JWT", expiredRawToken, jwt.ErrTokenIsExpired}, | |
{"malformed JWT", badRawToken, jws.ErrNotCompact}, // this might require fix in jws package | |
} | |
for _, testCase := range testCases { | |
w, err := jws.ParseJWT(testCase.rawJWT) | |
if err != nil { | |
if err != testCase.expectedError { | |
t.Fatal(err) | |
} | |
} | |
// see ValidateJWT below in the gist. | |
if err = ValidateJWT(w); err != testCase.expectedError { | |
t.Fatalf("%s: expected error: %#v got: %#v", testCase.name, testCase.expectedError, err) | |
} | |
} | |
} | |
// ValidateJWT checks whether our required fields exist on the JWT. | |
// The signature is also verified (uses RS384 signing method). | |
// It uses the public key set by UseRSAPublicKey. | |
func ValidateJWT(token jwt.JWT) (err error) { | |
defer func() { | |
if r := recover(); r != nil { | |
err = errors.New(fmt.Sprint(r)) | |
} | |
}() | |
claims := token.Claims() | |
// is expired? | |
err = claims.Validate(time.Now().UTC(), Expiration, 0) | |
if err != nil { | |
return err | |
} | |
validator := jws.NewValidator(nil, time.Duration(0), 0, hasRequiredKeys) | |
return token.Validate(rsaPub, crypto.SigningMethodRS384, validator) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment