-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_test.go
100 lines (93 loc) · 2.11 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
95
96
97
98
99
100
package auth
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"reflect"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
)
func TestJWT_Generate(t *testing.T) {
type args struct {
claims jwt.MapClaims
expDate int64
}
tests := []struct {
name string
fields []OptionJWT
args args
wantValidateErr bool
wantErr bool
}{
{
name: "empty",
fields: []OptionJWT{},
args: args{},
wantValidateErr: false,
wantErr: true,
},
{
name: "simple false",
fields: []OptionJWT{
WithSecretByte([]byte("pass1234")),
WithMethod(jwt.SigningMethodHS256),
},
args: args{},
wantValidateErr: false,
wantErr: false,
},
{
name: "with 1 hour",
fields: []OptionJWT{
WithSecretByte([]byte("pass1234")),
WithMethod(jwt.SigningMethodHS256),
},
args: args{
claims: map[string]interface{}{"info": "hello"},
expDate: time.Now().Add(time.Hour).Unix(),
},
wantValidateErr: false,
wantErr: false,
},
{
name: "rsa",
fields: func() []OptionJWT {
v, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil
}
return []OptionJWT{
WithRSAPrivateKey(v),
WithMethod(jwt.SigningMethodRS256),
}
}(),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tr, err := NewJWT(append(tt.fields, WithKID("test"))...)
if err != nil {
if tt.wantErr {
return
}
t.Fatalf("JWT.Generate() error = %v", err)
}
fmt.Println(tr.kid)
got, err := tr.Generate(tt.args.claims, tt.args.expDate)
if (err != nil) != tt.wantErr {
t.Fatalf("JWT.Generate() error = %v, wantErr %v", err, tt.wantErr)
}
fmt.Println(got)
claims := jwt.MapClaims{}
_, err = tr.Parse(got, &claims)
if (err != nil) != tt.wantValidateErr {
t.Fatalf("JWT.Validate() error = %v, wantValidateErr %v", err, tt.wantValidateErr)
}
delete(claims, "exp")
if len(tt.args.claims) != 0 && !reflect.DeepEqual(tt.args.claims, claims) {
t.Fatalf("claims %#v, want %#v", claims, tt.args.claims)
}
})
}
}