golang-jwt / jwt

Community maintained clone of https://github.com/dgrijalva/jwt-go

Home Page:https://golang-jwt.github.io/jwt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possible error in token parsing examples

zeim839 opened this issue · comments

I am using a modified version of the doc example here. My code is as follows:

func VerifyJWT(secret string, tokenStr string) (string, int, error) {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		return []byte(secret), nil
	})

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
                return claims["address"].(string), claims["user_id"].(int), nil
	}

	return "", 0, err
}

When given a bad tokenStr, the example breaks at the if claims, ok := ... clause and prints an error. However, I am getting a runtime panic:

runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:220 (0x404d4f5)
	panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:818 (0x404d4c5)
	sigpanic: panicmem()
/Users/DIR/jwt.go:28 (0x45b8c85)
	VerifyJWT: if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {

However, the error is resolved when I test for err != nil:

func VerifyJWT(secret string, tokenStr string) (string, int, error) {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		return []byte(secret), nil
	})

        // TEST FOR ERR
        if err != nil {
                return "", 0, err
        }

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
                 return claims["address"].(string), claims["user_id"].(int), nil
	}

	return "", 0, err
}

I am testing with secret="0x123456789" and tokenStr="hello". err is token is malformed token contains an invalid number of segments.

Thanks for filing an issue, you're absolutely right, we should update the examples to always check for an error.

It's a Go best practice to check the error and only if there's no error assume the return value is valid.

We'll get this updated!