forked from cristalhq/jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
179 lines (144 loc) · 5.85 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package jwt_test
import (
"encoding/json"
"fmt"
"time"
"github.com/cristalhq/jwt/v4"
)
func ExampleSignAndVerify() {
// create a Signer (HMAC in this example)
key := []byte(`secret`)
signer, err := jwt.NewSignerHS(jwt.HS256, key)
checkErr(err)
// create claims (you can create your own, see: Example_BuildUserClaims)
claims := &jwt.RegisteredClaims{
Audience: []string{"admin"},
ID: "random-unique-string",
}
// create a Builder
builder := jwt.NewBuilder(signer)
// and build a Token
token, err := builder.Build(claims)
checkErr(err)
// here is token as a string
var _ string = token.String()
// create a Verifier (HMAC in this example)
verifier, err := jwt.NewVerifierHS(jwt.HS256, key)
checkErr(err)
// parse and verify a token
tokenBytes := token.Bytes()
newToken, err := jwt.Parse(tokenBytes, verifier)
checkErr(err)
// or just verify it's signature
err = verifier.Verify(newToken)
checkErr(err)
// also you can parse without verify (NOT RECOMMENDED!)
newToken, err = jwt.ParseNoVerify(tokenBytes)
checkErr(err)
// get REGISTERED claims
var newClaims jwt.RegisteredClaims
errClaims := json.Unmarshal(newToken.Claims(), &newClaims)
checkErr(errClaims)
// or parse only claims
errParseClaims := jwt.ParseClaims(tokenBytes, verifier, &newClaims)
checkErr(errParseClaims)
// verify claims as you wish
var _ bool = newClaims.IsForAudience("admin")
var _ bool = newClaims.IsValidAt(time.Now())
// Output:
}
func ExampleBuild() {
key := []byte(`secret`)
signer, _ := jwt.NewSignerHS(jwt.HS256, key)
builder := jwt.NewBuilder(signer)
claims := &jwt.RegisteredClaims{
Audience: []string{"admin"},
ID: "random-unique-string",
}
token, err := builder.Build(claims)
checkErr(err)
fmt.Printf("Token %s\n", token.String())
fmt.Printf("Algorithm %s\n", token.Header().Algorithm)
fmt.Printf("Type %s\n", token.Header().Type)
fmt.Printf("Claims %s\n", token.Claims())
fmt.Printf("HeaderPart %s\n", token.HeaderPart())
fmt.Printf("ClaimsPart %s\n", token.ClaimsPart())
fmt.Printf("PayloadPart %s\n", token.PayloadPart())
fmt.Printf("SignaturePart %s\n", token.SignaturePart())
// Output:
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0.uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o
// Algorithm HS256
// Type JWT
// Claims {"jti":"random-unique-string","aud":"admin"}
// HeaderPart eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
// ClaimsPart eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0
// PayloadPart eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0
// SignaturePart uNaqGEggmy02lZq8FM7KoUKXhOy-zrSF7inYuzIET9o
}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIn0
type userClaims struct {
jwt.RegisteredClaims
IsAdministrator bool `json:"is_admin"`
Email string `json:"email"`
}
func ExampleBuild_WithUserClaims() {
key := []byte(`secret`)
signer, _ := jwt.NewSignerHS(jwt.HS256, key)
builder := jwt.NewBuilder(signer)
claims := &userClaims{
RegisteredClaims: jwt.RegisteredClaims{
Audience: []string{"admin"},
ID: "random-unique-string",
},
IsAdministrator: true,
Email: "[email protected]",
}
token, err := builder.Build(claims)
checkErr(err)
fmt.Printf("Claims %v\n", string(token.Claims()))
fmt.Printf("Payload %v\n", string(token.PayloadPart()))
fmt.Printf("Token %v\n", string(token.Bytes()))
// Output:
// Claims {"jti":"random-unique-string","aud":"admin","is_admin":true,"email":"[email protected]"}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIiwiaXNfYWRtaW4iOnRydWUsImVtYWlsIjoiZm9vQGJhci5iYXoifQ
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJyYW5kb20tdW5pcXVlLXN0cmluZyIsImF1ZCI6ImFkbWluIiwiaXNfYWRtaW4iOnRydWUsImVtYWlsIjoiZm9vQGJhci5iYXoifQ.oKE62_k3bqAlKwdBJDBJq5DQ_0FvpNv6e1u6hF_ShQs
}
func ExampleParse() {
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`)
key := []byte(`secret`)
verifier, _ := jwt.NewVerifierHS(jwt.HS256, key)
token, err := jwt.Parse(rawToken, verifier)
checkErr(err)
fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
fmt.Printf("Claims %v\n", string(token.Claims()))
fmt.Printf("Payload %v\n", string(token.PayloadPart()))
fmt.Printf("Token %v\n", string(token.Bytes()))
// Output:
// Algorithm HS256
// Type JWT
// Claims {"aud":"admin","jti":"random-unique-string"}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
}
func ExampleParseNoVerify() {
rawToken := []byte(`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs`)
token, err := jwt.ParseNoVerify(rawToken)
checkErr(err)
fmt.Printf("Algorithm %v\n", token.Header().Algorithm)
fmt.Printf("Type %v\n", token.Header().Type)
fmt.Printf("Claims %v\n", string(token.Claims()))
fmt.Printf("Payload %v\n", string(token.PayloadPart()))
fmt.Printf("Token %v\n", string(token.Bytes()))
// Output:
// Algorithm HS256
// Type JWT
// Claims {"aud":"admin","jti":"random-unique-string"}
// Payload eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0
// Token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhZG1pbiIsImp0aSI6InJhbmRvbS11bmlxdWUtc3RyaW5nIn0.dv9-XpY9P8ypm1uWQwB6eKvq3jeyodLA7brhjsf4JVs
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}