Skip to content

Returning the right error in jwt.NewParser #498

@avdempsey

Description

@avdempsey

I'm trying to catch errors from parsing JWTs so I can return a nice 401 to tell the client to try re-authorizing, but it looks like NewParser favors passing through the errors generated by dgrijalva/jwt-go (which are a little more complicated than your garden variety error) instead of passing kit's own set of JWT errors (defined in auth/jwt/middleware.go).

In auth/jwt/middleware.go we have the following bit:

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if token.Method != method {
		return nil, ErrUnexpectedSigningMethod
	}

	return keyFunc(token)
})
if err != nil {
	if e, ok := err.(*jwt.ValidationError); ok && e.Inner != nil {
		if e.Errors&jwt.ValidationErrorMalformed != 0 {
			// Token is malformed
			return nil, ErrTokenMalformed
		} else if e.Errors&jwt.ValidationErrorExpired != 0 {
			// Token is expired
			return nil, ErrTokenExpired
		} else if e.Errors&jwt.ValidationErrorNotValidYet != 0 {
			// Token is not active yet
			return nil, ErrTokenNotActive
		}

		return nil, e.Inner
	}

	return nil, err
}

Many times the error thrown by the dgrijalva/jwt-go Parse function (pointers to ValidationError structs) will have a e.Inner == nil. E.g.:

func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
	parts := strings.Split(tokenString, ".")
	if len(parts) != 3 {
		return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
	}
...

These errors will fall through the ifs above until we reach return nil, err. So for errors generated by the NewValidationError function, kit won't use its own JWT errors.

Is this working as designed?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions