Skip to content

Commit

Permalink
Handle ValidationError returned by keyFunc in jwt.ParseWithClaims
Browse files Browse the repository at this point in the history
Previously, returning a `jwt.ValidationError` from `jwt.Parse()` or
`jwt.ParseWithClaims()` would result values the error to be
ignored.
For example, when testing the signature while parsing the token, it
was not possible to return `jwt.ValidationErrorSignatureInvalid`.
The documentation shows an example for returning an `errors.Error`,
but this is not enough.

We change the `jwt.ParseWithClaims()`-function and check whether the
returned error from the `KeyFunc` is already a
`jwt.ValidationError`-type and return as-is.

This allows us to do the following:

  token, err := jwt.ParseWithClaims(authToken, claims, func(token
    *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
        vErr := new(jwt.ValidationError)
        vErr.Errors = jwt.ValidationErrorSignatureInvalid
        vErr.Inner = fmt.Errorf("invalid signature")
        return nil, vErr
    }
    return []byte(MySecret), nil
  })

The idea is to then be able to check the `Errors`-member:

  } else if ve.Errors&jwt.ValidationErrorSignatureInvalid != 0 {
    return fmt.Errorf("Authentication Token has invalid signature")
  }
  • Loading branch information
Geert Vanderkelen committed Jun 28, 2017
1 parent a539ee1 commit cb914dd
Showing 1 changed file with 3 additions and 0 deletions.
3 changes: 3 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf
}
if key, err = keyFunc(token); err != nil {
// keyFunc returned an error
if ve, ok := err.(*ValidationError); ok {
return token, ve
}
return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
}

Expand Down

0 comments on commit cb914dd

Please sign in to comment.