forked from lestrrat-go/jwx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_example_test.go
335 lines (294 loc) · 8.61 KB
/
jwt_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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package examples_test
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"log"
"time"
"github.com/lestrrat-go/jwx/internal/json"
"github.com/lestrrat-go/jwx/jwk"
"github.com/lestrrat-go/jwx/jwt/openid"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
)
const aLongLongTimeAgo = 233431200
//nolint:govet
func ExampleJWT_ParseWithJWKS() {
privKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Printf("failed to generate private key: %s\n", err)
return
}
{
// Case 1: the Token is signed with a specific key, denoted by "kid".
// In this case you must obtain a KeySet with proper "kids".
//
// token -> { "kid": "mykey", .... values ... }
// key set -> [ { ... }, { ... }, { "kid": "mykey", ... } ]
//
// Then jwt.Parse() will automatically find the matching key
var payload []byte
var keyset jwk.Set
{ // Preparation:
// For demonstration purposes, we need to do some preparation
// Create a JWK key to sign the token (and also give a KeyID)
realKey, err := jwk.New(privKey)
if err != nil {
fmt.Printf("failed to create JWK: %s\n", err)
return
}
realKey.Set(jwk.KeyIDKey, `mykey`)
// Create the token
token := jwt.New()
token.Set(`foo`, `bar`)
// Sign the token and generate a payload
signed, err := jwt.Sign(token, jwa.RS256, realKey)
if err != nil {
fmt.Printf("failed to generate signed payload: %s\n", err)
return
}
// This is what you typically get as a signed JWT from a server
payload = signed
// Now create a key set that users will use to verity the signed payload against
// Normally these keys are available somewhere like https://www.googleapis.com/oauth2/v3/certs
pubKey, err := jwk.New(privKey.PublicKey)
if err != nil {
fmt.Printf("failed to create JWK: %s\n", err)
return
}
// Remember, the key must have the proper "kid", and "alg"
pubKey.Set(jwk.AlgorithmKey, jwa.RS256)
pubKey.Set(jwk.KeyIDKey, "mykey")
// For demonstration purposes, we also create a bogus key
bogusKey := jwk.NewSymmetricKey()
bogusKey.Set(jwk.AlgorithmKey, jwa.NoSignature)
bogusKey.Set(jwk.KeyIDKey, "otherkey")
// This key set contains two keys, the first one is the correct one
keyset = jwk.NewSet()
keyset.Add(pubKey)
keyset.Add(bogusKey)
}
{ // Actual verification:
// FINALLY. This is how you Parse and verify the payload.
// Key IDs are automatically matched.
// There was a lot of code above, but as a consumer, below is really all you need
// to write in your code
token, err := jwt.Parse(
payload,
// Tell the parser that you want to use this keyset
jwt.WithKeySet(keyset),
)
if err != nil {
fmt.Printf("failed to parse payload: %s\n", err)
}
_ = token
}
}
{
// Case 2: For whatever reason, we don't have a "kid" specified.
// Normally, this is an error, because we don't know how to select a key.
// But if we have only one key in the KeySet, you can explicitly ask
// jwt.Parse to "trust" the KeySet, and use the single key in the
// key set. It would be an error if you have multiple keys in the KeySet.
var payload []byte
var keyset jwk.Set
{ // Preparation:
// Unlike our previous example, we DO NOT want to sign the payload.
// Therefore we do NOT set the "kid" value
realKey, err := jwk.New(privKey)
if err != nil {
fmt.Printf("failed to create JWK: %s\n", err)
return
}
// Create the token
token := jwt.New()
token.Set(`foo`, `bar`)
// Sign the token and generate a payload
signed, err := jwt.Sign(token, jwa.RS256, realKey)
if err != nil {
fmt.Printf("failed to generate signed payload: %s\n", err)
return
}
// This is what you typically get as a signed JWT from a server
payload = signed
// Now create a key set that users will use to verity the signed payload against
// Normally these keys are available somewhere like https://www.googleapis.com/oauth2/v3/certs
pubKey, err := jwk.New(privKey.PublicKey)
if err != nil {
fmt.Printf("failed to create JWK: %s\n", err)
return
}
pubKey.Set(jwk.AlgorithmKey, jwa.RS256)
// This JWKS can *only* have 1 key.
keyset = jwk.NewSet()
keyset.Add(pubKey)
}
{
token, err := jwt.Parse(
payload,
// Tell the parser that you want to use this keyset
jwt.WithKeySet(keyset),
// Tell the parser that you can trust this KeySet, and that
// you want to use the sole key in it
jwt.UseDefaultKey(true),
)
if err != nil {
fmt.Printf("failed to parse payload: %s\n", err)
}
_ = token
}
}
// OUTPUT:
}
func ExampleJWT_Sign() {
privKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Printf("failed to generate private key: %s\n", err)
return
}
var payload []byte
{ // Create signed payload
token := jwt.New()
token.Set(`foo`, `bar`)
payload, err = jwt.Sign(token, jwa.RS256, privKey)
if err != nil {
fmt.Printf("failed to generate signed payload: %s\n", err)
return
}
}
{ // Parse signed payload, and perform (1) verification of the signature
// and (2) validation of the JWT token
// Validation can be performed in a separate step using `jwt.Validate`
token, err := jwt.Parse(
payload,
jwt.WithValidate(true),
jwt.WithVerify(jwa.RS256, &privKey.PublicKey),
)
if err != nil {
fmt.Printf("failed to parse JWT token: %s\n", err)
return
}
buf, err := json.MarshalIndent(token, "", " ")
if err != nil {
fmt.Printf("failed to generate JSON: %s\n", err)
return
}
fmt.Printf("%s\n", buf)
}
// OUTPUT:
// {
// "foo": "bar"
// }
}
func ExampleJWT_Token() {
t := jwt.New()
t.Set(jwt.SubjectKey, `https://github.com/lestrrat-go/jwx/jwt`)
t.Set(jwt.AudienceKey, `Golang Users`)
t.Set(jwt.IssuedAtKey, time.Unix(aLongLongTimeAgo, 0))
t.Set(`privateClaimKey`, `Hello, World!`)
buf, err := json.MarshalIndent(t, "", " ")
if err != nil {
fmt.Printf("failed to generate JSON: %s\n", err)
return
}
fmt.Printf("%s\n", buf)
fmt.Printf("aud -> '%s'\n", t.Audience())
fmt.Printf("iat -> '%s'\n", t.IssuedAt().Format(time.RFC3339))
if v, ok := t.Get(`privateClaimKey`); ok {
fmt.Printf("privateClaimKey -> '%s'\n", v)
}
fmt.Printf("sub -> '%s'\n", t.Subject())
// OUTPUT:
// {
// "aud": [
// "Golang Users"
// ],
// "iat": 233431200,
// "privateClaimKey": "Hello, World!",
// "sub": "https://github.com/lestrrat-go/jwx/jwt"
// }
// aud -> '[Golang Users]'
// iat -> '1977-05-25T18:00:00Z'
// privateClaimKey -> 'Hello, World!'
// sub -> 'https://github.com/lestrrat-go/jwx/jwt'
}
func ExampleJWT_SignToken() {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Printf("failed to generate private key: %s", err)
return
}
t := jwt.New()
{
// Signing a token (using raw rsa.PrivateKey)
signed, err := jwt.Sign(t, jwa.RS256, key)
if err != nil {
log.Printf("failed to sign token: %s", err)
return
}
_ = signed
}
{
// Signing a token (using JWK)
jwkKey, err := jwk.New(key)
if err != nil {
log.Printf("failed to create JWK key: %s", err)
return
}
signed, err := jwt.Sign(t, jwa.RS256, jwkKey)
if err != nil {
log.Printf("failed to sign token: %s", err)
return
}
_ = signed
}
// OUTPUT:
}
func ExampleJWT_OpenIDToken() {
t := openid.New()
t.Set(jwt.SubjectKey, `https://github.com/lestrrat-go/jwx/jwt`)
t.Set(jwt.AudienceKey, `Golang Users`)
t.Set(jwt.IssuedAtKey, time.Unix(aLongLongTimeAgo, 0))
t.Set(`privateClaimKey`, `Hello, World!`)
addr := openid.NewAddress()
addr.Set(openid.AddressPostalCodeKey, `105-0011`)
addr.Set(openid.AddressCountryKey, `日本`)
addr.Set(openid.AddressRegionKey, `東京都`)
addr.Set(openid.AddressLocalityKey, `港区`)
addr.Set(openid.AddressStreetAddressKey, `芝公園 4-2-8`)
if err := t.Set(openid.AddressKey, addr); err != nil {
fmt.Printf("failed to set address: %s\n", err)
return
}
buf, err := json.MarshalIndent(t, "", " ")
if err != nil {
fmt.Printf("failed to generate JSON: %s\n", err)
return
}
fmt.Printf("%s\n", buf)
t2, err := jwt.Parse(buf, jwt.WithToken(openid.New()))
if err != nil {
fmt.Printf("failed to parse JSON: %s\n", err)
return
}
if _, ok := t2.(openid.Token); !ok {
fmt.Printf("using jwt.WithToken(openid.New()) creates an openid.Token instance")
return
}
// OUTPUT:
// {
// "address": {
// "country": "日本",
// "locality": "港区",
// "postal_code": "105-0011",
// "region": "東京都",
// "street_address": "芝公園 4-2-8"
// },
// "aud": [
// "Golang Users"
// ],
// "iat": 233431200,
// "privateClaimKey": "Hello, World!",
// "sub": "https://github.com/lestrrat-go/jwx/jwt"
// }
}