Skip to content

Possible error in token parsing examples #309

@zeim839

Description

@zeim839

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions