Skip to content
This repository has been archived by the owner on May 21, 2022. It is now read-only.

json: cannot unmarshal object into Go value of type jwt.Claims #345

Open
rentateamdev1 opened this issue Jul 29, 2019 · 5 comments
Open

Comments

@rentateamdev1
Copy link

https://github.com/dgrijalva/jwt-go/blob/master/parser.go#L131
this decode code always returns decode error
json: cannot unmarshal object into Go value of type jwt.Claims
because claims variable is declared as interface not a struct

@dgrijalva
Copy link
Owner

jwt.Claims is an interface. The claims value you pass into the parser needs to be a concrete type. It's essentially passed directly through to the standard library JSON parser and will follow that behavior.

@rentateamdev1
Copy link
Author

rentateamdev1 commented Jul 30, 2019

The error is that json decoder could not decode to variable of type Claims, because Claims is an interface and decoder do not know what real type is
I wrote an example of code, based on https://github.com/dgrijalva/jwt-go/blob/master/parser.go#L131

With error: https://play.golang.org/p/WT5yd2X_iCI
Without error: https://play.golang.org/p/2NOnAf267HA

@kheraud
Copy link

kheraud commented Apr 8, 2020

@rentateamdev1 , use a pointer to your custom claim instead of a value one. An interface is a tuple (concrete type, value). If you use a pointer type (*MyCustomClaim) as the concrete type of your interface, encoding/json figures out the json tags of your struct.

var claims jwt.Claims = &MyCustomClaims{}
...
err := dec.Decode(&claims)

Or for your example with error : claims = &StandardClaims{}

@zhangguanzhang
Copy link

I used this is ok

func ParseToken(tokenStr string) (*Claims, error) {
	var claims *Claims
	token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return conf.JWTKey(), nil
	})

	if token != nil {
		if claims, ok := token.Claims.(*Claims); ok && token.Valid {
			return claims, nil
		}
	}

	return claims, err
}

@mieubrisse
Copy link

I'm not the OP, but @kheraud 's solution fixed this for me. The example for a custom claims type has this same logic, so maybe just a quick explanatory comment on the example could close this issue?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants