forked from dgrijalva/jwt-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec_test.go
65 lines (56 loc) · 1.88 KB
/
codec_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package jwt_test
import (
"bytes"
"encoding/json"
"reflect"
"testing"
"github.com/ezaurum/jwt-go/v4"
"github.com/ezaurum/jwt-go/v4/test"
)
func TestCustomCodec(t *testing.T) {
var customEncoderUsed = false
var encoder = func(ctx jwt.CodingContext, v interface{}) ([]byte, error) {
customEncoderUsed = true
if ctx.FieldDescriptor == jwt.HeaderFieldDescriptor {
return json.Marshal(v)
}
// encode as some random bytes
return []byte("abc123"), nil
}
var customDecoderUsed = false
var decoder = func(ctx jwt.CodingContext, data []byte, v interface{}) error {
customDecoderUsed = true
if ctx.FieldDescriptor == jwt.HeaderFieldDescriptor {
return json.Unmarshal(data, v)
}
// Ensure the value was encoded using the custom marshaler
if x := "abc123"; !bytes.Equal(data, []byte(x)) {
t.Errorf("Encoded data %v didn't match expectation %v", string(data), string(x))
}
// Parse it as if it were encoded correctly
return json.Unmarshal([]byte(`{"foo": "bar"}`), v)
}
privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key")
publicKey := privateKey.Public()
// Create and encode a token
var token = jwt.New(jwt.SigningMethodRS256)
token.Claims = jwt.MapClaims{"foo": "bar"}
tokenString, err := token.SignedString(privateKey, jwt.WithMarshaller(encoder))
if err != nil {
t.Fatalf("Unexpected error when encoding: %v", err)
}
if !customEncoderUsed {
t.Error("Custom encoder was not used as expected")
}
// Decode the token
parsedToken, err := jwt.Parse(tokenString, jwt.KnownKeyfunc(jwt.SigningMethodRS256, publicKey), jwt.WithUnmarshaller(decoder))
if err != nil {
t.Fatalf("Unexpected error when encoding: %v", err)
}
if !customDecoderUsed {
t.Error("Custom encoder was not used as expected")
}
if !reflect.DeepEqual(token.Claims, parsedToken.Claims) {
t.Errorf("Parsed token %v didn't match expectation %v", parsedToken.Claims, token.Claims)
}
}