-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
example_test.go
102 lines (84 loc) · 2.67 KB
/
example_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
101
102
package sjwt
import (
"fmt"
"time"
)
func Example() {
// Add Claims
claims := New()
claims.Set("username", "billymister")
claims.Set("account_id", 8675309)
// Generate jwt
secretKey := []byte("secret_key_here")
jwt := claims.Generate(secretKey)
fmt.Println(jwt)
}
func Example_parse() {
// Parse jwt
jwt := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
claims, _ := Parse(jwt)
// Get claims
name, _ := claims.GetStr("name")
fmt.Println(name)
// Output: John Doe
}
func Example_registeredClaims() {
// Add Claims
claims := New()
claims.SetTokenID() // UUID generated
claims.SetSubject("Subject Title") // Subject of the token
claims.SetIssuer("Google") // Issuer of the token
claims.SetAudience([]string{"Google", "Facebook"}) // Audience the toke is for
claims.SetIssuedAt(time.Now()) // IssuedAt in time, value is set in unix
claims.SetNotBeforeAt(time.Now().Add(time.Hour * 1)) // Token valid in 1 hour
claims.SetExpiresAt(time.Now().Add(time.Hour * 24)) // Token expires in 24 hours
// Generate jwt
secretKey := []byte("secret_key_here")
jwt := claims.Generate(secretKey)
fmt.Println(jwt)
}
func Example_publicClaims() {
// Add Claims
claims := New()
claims.Set("username", "billymister")
claims.Set("account_id", 8675309)
// Generate jwt
secretKey := []byte("secret_key_here")
jwt := claims.Generate(secretKey)
fmt.Println(jwt)
}
func Example_structToClaims() {
type Info struct {
Name string `json:"name"`
}
// Marshal your struct into claims
info := Info{Name: "Billy Mister"}
claims, _ := ToClaims(info)
// Generate jwt
secretKey := []byte("secret_key_here")
jwt := claims.Generate(secretKey)
fmt.Println(jwt)
// output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQmlsbHkgTWlzdGVyIn0.2FYrpCNy1tg_4UvimpSrgAy-nT9snh-l4w9VLz71b6Y
}
func Example_claimsToStruct() {
type Info struct {
Name string `json:"name"`
}
// Parse jwt
jwt := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQmlsbHkgTWlzdGVyIn0.2FYrpCNy1tg_4UvimpSrgAy-nT9snh-l4w9VLz71b6Y"
claims, _ := Parse(jwt)
// Marshal your struct into claims
info := Info{}
claims.ToStruct(&info)
name, _ := claims.GetStr("name")
fmt.Println(name)
// output: Billy Mister
}
func Example_verifySignature() {
secretKey := []byte("secret_key_here")
jwt := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQmlsbHkgTWlzdGVyIn0.2FYrpCNy1tg_4UvimpSrgAy-nT9snh-l4w9VLz71b6Y"
// Pass jwt and secret key to verify
verified := Verify(jwt, secretKey)
fmt.Println(verified)
// output: true
}