-
An error occurs for this simple code: import (
"testing"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
)
type cc struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
func TestParseWClaims(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, cc{Foo: "value"})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte("xxxx"))
assert.Nil(t, err, "Sign failed")
parser := &jwt.Parser{}
var c cc
ttoken, err := parser.ParseWithClaims(tokenString, c, func(t *jwt.Token) (any, error) { return []byte("xxxx"), nil })
t.Logf("%+v", ttoken.Claims)
assert.Nil(t, err, "Parse claims")
assert.Equal(t, ttoken.Claims.(cc).Foo, "value")
} Produces:
The error occurs calling type cc struct {
Foo string `json:"foo"`
jwt.RegisteredClaims
}
func TestJsonDec(t *testing.T) {
bs := []byte(`{"Foo":"value"}`)
func(claim jwt.Claims) {
c := claim
dec := json.NewDecoder(bytes.NewBuffer(bs))
e := dec.Decode(&c)
assert.Nil(t, e)
}(c)
} Apart from using the |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Pass the memory address of
and then assert Claims to your type (*cc) in this case, e.g.,
There is an example of custom claims here if it helps: Lines 101 to 109 in 8aa5d6c |
Beta Was this translation helpful? Give feedback.
-
ttoken, err := jwt.ParseWithClaims(tokenString, &c, func(t *jwt.Token) (any, error) { return []byte("xxxx"), nil }) I get jwt_test.go:63: &{Foo:value RegisteredClaims:{Issuer: Subject: Audience:[] ExpiresAt:<nil> NotBefore:<nil> IssuedAt:<nil> ID:}}
panic: interface conversion: jwt.Claims is *auth.cc, not auth.cc [recovered]
panic: interface conversion: jwt.Claims is *auth.cc, not auth.cc |
Beta Was this translation helpful? Give feedback.
-
A few suggestions,
- assert.Equal(t, ttoken.Claims.(cc).Foo, "value")
+ customClaims, ok := ttoken.Claims.(cc)
ttoken.Claims.(*cc) |
Beta Was this translation helpful? Give feedback.
-
Moving this to the Q&A discussion. |
Beta Was this translation helpful? Give feedback.
Pass the memory address of
c
, e.g.,and then assert Claims to your type (*cc) in this case, e.g.,
There is an example of custom claims here if it helps:
jwt/http_example_test.go
Lines 101 to 109 in 8aa5d6c