-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_test.go
94 lines (90 loc) · 2.15 KB
/
jwt_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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package jwt
import (
"fmt"
"reflect"
"strings"
"testing"
"time"
jwtgo "github.com/dgrijalva/jwt-go"
)
func TestJWT_Create(t *testing.T) {
type payload struct {
id int
role string
}
for _, tc := range []struct {
name string
data *payload
}{
{
name: "should has 3 components: header, payload, signature",
data: &payload{id: 1, role: "admin"},
},
} {
t.Run(fmt.Sprintf("[case] %s", tc.name), func(t *testing.T) {
token, _ := New("secret").Create(tc.data)
got := len(strings.Split(string(token), "."))
if got != 3 {
t.Errorf("got %v; want 3", got)
}
})
}
}
func TestJWT_Validate(t *testing.T) {
type payload struct {
ID int `json:"id"`
Role string `json:"role"`
}
type args struct {
data *payload
create func(data interface{}) (string, error)
}
cases := []struct {
name string
args args
wantPayload map[string]interface{}
wantErr bool
}{
{
name: "signature incorrect",
args: args{
data: &payload{ID: 1, Role: "admin"},
create: func(data interface{}) (string, error) {
token := jwtgo.New(jwtgo.GetSigningMethod("HS256"))
token.Claims = &customClaim{data, jwtgo.StandardClaims{}}
return token.SignedString([]byte("fake_secret"))
},
},
wantErr: true,
},
{
name: "base case",
args: args{
data: &payload{ID: 10, Role: "admin"},
create: func(data interface{}) (string, error) {
token := jwtgo.New(jwtgo.GetSigningMethod("HS256"))
token.Claims = &customClaim{data, jwtgo.StandardClaims{}}
return token.SignedString([]byte("secret"))
},
},
wantErr: false,
wantPayload: map[string]interface{}{
"id": float64(10),
"role": "admin",
},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
toker := jwt{secret: "secret", expiresAt: time.Second * 10}
token, _ := tc.args.create(tc.args.data)
pl, err := toker.Validate(token)
if (err != nil) != tc.wantErr {
t.Fatalf("jwt.Validate() got error: %v; want %v", err, tc.wantErr)
}
if !tc.wantErr && !reflect.DeepEqual(pl, tc.wantPayload) {
t.Fatalf("jwt.Validate() got payload: %v; want %v", pl, tc.wantPayload)
}
})
}
}