@@ -8,9 +8,44 @@ import (
8
8
"encoding/base64"
9
9
"github.com/CarsonSlovoka/go-jwt"
10
10
"github.com/CarsonSlovoka/go-jwt/parser"
11
+ "github.com/CarsonSlovoka/go-jwt/validator"
11
12
"testing"
12
13
)
13
14
15
+ func TestNew_hmac (t * testing.T ) {
16
+ token := jwt .NewWithClaims (
17
+ jwt .SigningMethodHMAC256 ,
18
+
19
+ // 指定所有你想要的Claims
20
+ // 如果要擴展可以用MapClaims或者自定義struct把RegisteredClaims加入,可以參考:
21
+ // https://github.com/CarsonSlovoka/jwt/blob/5ff3ea21d7624f73baf3f2cd7c89ba5p a4129dedb/validator/validator_test.go#L11-L37
22
+ jwt.RegisteredClaims {
23
+ Issuer : "c.example.com" ,
24
+ },
25
+ )
26
+ // token.Header["xx"] = "" // 如果有需要自定義Header可以後補上
27
+ privateKey := []byte ("key" )
28
+ bsSignature , err := token .SignedBytes (privateKey )
29
+ if err != nil {
30
+ t .Fatal (err )
31
+ }
32
+ p := parser .New (func (v * validator.Validator ) {
33
+ v .ExpectedIssuer = "c.example.com"
34
+ v .VerifyIat = true
35
+ })
36
+ vdFunc , err := p .Parse (string (bsSignature ), func (method string ) (jwt.ISigningMethod , error ) {
37
+ return jwt .SigningMethodHMAC256 , nil
38
+ })
39
+ if err != nil {
40
+ t .Fatal (err )
41
+ }
42
+ if err = vdFunc (nil , nil , func (token * jwt.Token ) (key any , err error ) {
43
+ return privateKey , nil
44
+ }); err != nil {
45
+ t .Fatal (err )
46
+ }
47
+ }
48
+
14
49
func TestToken_SignedBytes_hmac (t * testing.T ) {
15
50
token := jwt .NewWithClaims (jwt .SigningMethodHMAC256 , jwt.MapClaims {})
16
51
privateKey := []byte ("helloWorld" )
@@ -61,6 +96,29 @@ func TestToken_SignedBytes_rsa(t *testing.T) {
61
96
}
62
97
}
63
98
99
+ func TestNew_rsa (t * testing.T ) {
100
+ rsaKey , _ := rsa .GenerateKey (rand .Reader , 2048 )
101
+ token := jwt .New (jwt .SigningMethodRSA256 )
102
+ bsSignature , err := token .SignedBytes (rsaKey )
103
+ if err != nil {
104
+ t .Fatal (err )
105
+ }
106
+ vdFunc , err := parser .New ().Parse (
107
+ string (bsSignature ),
108
+ func (method string ) (jwt.ISigningMethod , error ) {
109
+ return jwt .SigningMethodRSA256 , nil
110
+ },
111
+ )
112
+ if err != nil {
113
+ t .Fatal (err )
114
+ }
115
+ if err = vdFunc (nil , nil , func (token * jwt.Token ) (key any , err error ) {
116
+ return & rsaKey .PublicKey , nil
117
+ }); err != nil {
118
+ t .Fatal (err )
119
+ }
120
+ }
121
+
64
122
func TestNew_ed25519 (t * testing.T ) {
65
123
token := jwt .New (& jwt.SigningMethodED25519 {})
66
124
publicKey , privateKey , _ := ed25519 .GenerateKey (rand .Reader )
0 commit comments