-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathjwtverifier.go
417 lines (345 loc) · 10.3 KB
/
jwtverifier.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*******************************************************************************
* Copyright 2018 - Present Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package jwtverifier
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"github.com/okta/okta-jwt-verifier-golang/v2/adaptors"
"github.com/okta/okta-jwt-verifier-golang/v2/adaptors/lestrratGoJwx"
"github.com/okta/okta-jwt-verifier-golang/v2/discovery"
"github.com/okta/okta-jwt-verifier-golang/v2/discovery/oidc"
"github.com/okta/okta-jwt-verifier-golang/v2/errors"
"github.com/okta/okta-jwt-verifier-golang/v2/utils"
)
var (
regx = regexp.MustCompile(`[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+\.?([a-zA-Z0-9-_]+)[/a-zA-Z0-9-_]+?$`)
)
type JwtVerifier struct {
Issuer string
ClaimsToValidate map[string]string
Discovery discovery.Discovery
Adaptor adaptors.Adaptor
Client *http.Client
// Cache allows customization of the cache used to store resources
Cache func(func(string) (interface{}, error), time.Duration, time.Duration) (utils.Cacher, error)
metadataCache utils.Cacher
leeway int64
Timeout time.Duration
Cleanup time.Duration
}
type Jwt struct {
Claims map[string]interface{}
}
func (j *JwtVerifier) fetchMetaData(url string) (interface{}, error) {
resp, err := j.Client.Get(url)
if err != nil {
return nil, fmt.Errorf("request for metadata was not successful: %w", err)
}
defer resp.Body.Close()
ok := resp.StatusCode >= 200 && resp.StatusCode < 300
if !ok {
return nil, fmt.Errorf("request for metadata %q was not HTTP 2xx OK, it was: %d", url, resp.StatusCode)
}
metadata := make(map[string]interface{})
if err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {
return nil, err
}
return metadata, nil
}
func (j *JwtVerifier) New() (*JwtVerifier, error) {
// Default to OIDC discovery if none is defined
if j.Discovery == nil {
disc := oidc.Oidc{}
j.Discovery = disc.New()
}
if j.Timeout == 0 {
j.Timeout = 5 * time.Minute
}
if j.Cleanup == 0 {
j.Cleanup = 10 * time.Minute
}
if j.Client == nil {
j.Client = http.DefaultClient
}
if j.Cache == nil {
j.Cache = utils.NewDefaultCache
}
// Default to LestrratGoJwx Adaptor if none is defined
if j.Adaptor == nil {
adaptor := &lestrratGoJwx.LestrratGoJwx{Cache: j.Cache, Timeout: j.Timeout, Cleanup: j.Cleanup, Client: j.Client}
adp, err := adaptor.New()
if err != nil {
return nil, err
}
j.Adaptor = adp
}
// Default to PT2M Leeway
j.leeway = 120
var err error
metadataCache, err := j.Cache(j.fetchMetaData, j.Timeout, j.Cleanup)
if err != nil {
return nil, err
}
j.metadataCache = metadataCache
return j, nil
}
func (j *JwtVerifier) SetLeeway(duration string) {
dur, _ := time.ParseDuration(duration)
j.leeway = int64(dur.Seconds())
}
func (j *JwtVerifier) SetTimeOut(duration time.Duration) {
j.Timeout = duration
}
func (j *JwtVerifier) SetCleanUp(duration time.Duration) {
j.Cleanup = duration
}
func (j *JwtVerifier) VerifyAccessToken(jwt string) (*Jwt, error) {
validJwt, err := j.isValidJwt(jwt)
if !validJwt {
return nil, fmt.Errorf("token is not valid: %w", err)
}
resp, err := j.decodeJwt(jwt)
if err != nil {
return nil, err
}
token := resp.(map[string]interface{})
myJwt := Jwt{
Claims: token,
}
err = j.validateIss(token["iss"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issuer` was not able to be validated. %w", err)
}
err = j.validateAudience(token["aud"])
if err != nil {
return &myJwt, fmt.Errorf("the `Audience` was not able to be validated. %w", err)
}
err = j.validateClientId(token["cid"])
if err != nil {
return &myJwt, fmt.Errorf("the `Client Id` was not able to be validated. %w", err)
}
err = j.validateExp(token["exp"])
if err != nil {
return &myJwt, fmt.Errorf("the `Expiration` was not able to be validated. %w", err)
}
err = j.validateIat(token["iat"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issued At` was not able to be validated. %w", err)
}
return &myJwt, nil
}
func (j *JwtVerifier) decodeJwt(jwt string) (interface{}, error) {
metaData, err := j.getMetaData()
if err != nil {
return nil, err
}
jwksURI, ok := metaData["jwks_uri"].(string)
if !ok {
return nil, fmt.Errorf("failed to decode JWT: missing 'jwks_uri' from metadata")
}
resp, err := j.Adaptor.Decode(jwt, jwksURI)
if err != nil {
return nil, fmt.Errorf("could not decode token: %w", err)
}
return resp, nil
}
func (j *JwtVerifier) VerifyIdToken(jwt string) (*Jwt, error) {
validJwt, err := j.isValidJwt(jwt)
if !validJwt {
return nil, fmt.Errorf("token is not valid: %w", err)
}
resp, err := j.decodeJwt(jwt)
if err != nil {
return nil, err
}
token := resp.(map[string]interface{})
myJwt := Jwt{
Claims: token,
}
err = j.validateIss(token["iss"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issuer` was not able to be validated. %w", err)
}
err = j.validateAudience(token["aud"])
if err != nil {
return &myJwt, fmt.Errorf("the `Audience` was not able to be validated. %w", err)
}
err = j.validateExp(token["exp"])
if err != nil {
return &myJwt, fmt.Errorf("the `Expiration` was not able to be validated. %w", err)
}
err = j.validateIat(token["iat"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issued At` was not able to be validated. %w", err)
}
err = j.validateNonce(token["nonce"])
if err != nil {
return &myJwt, fmt.Errorf("the `Nonce` was not able to be validated. %w", err)
}
return &myJwt, nil
}
func (j *JwtVerifier) GetDiscovery() discovery.Discovery {
return j.Discovery
}
func (j *JwtVerifier) GetAdaptor() adaptors.Adaptor {
return j.Adaptor
}
func (j *JwtVerifier) validateNonce(nonce interface{}) error {
if nonce == nil {
nonce = ""
}
if nonce != j.ClaimsToValidate["nonce"] {
return fmt.Errorf("nonce: %s does not match %s", nonce, j.ClaimsToValidate["nonce"])
}
return nil
}
func (j *JwtVerifier) validateAudience(audience interface{}) error {
// Audience is optional, it will be validated if it is present in the ClaimsToValidate array
if expectedAudience, exists := j.ClaimsToValidate["aud"]; !exists || audience == expectedAudience {
return nil
}
switch v := audience.(type) {
case string:
if v != j.ClaimsToValidate["aud"] {
return fmt.Errorf("aud: %s does not match %s", v, j.ClaimsToValidate["aud"])
}
case []string:
for _, element := range v {
if element == j.ClaimsToValidate["aud"] {
return nil
}
}
return fmt.Errorf("aud: %s does not match %s", v, j.ClaimsToValidate["aud"])
case []interface{}:
for _, e := range v {
element, ok := e.(string)
if !ok {
return fmt.Errorf("unknown type for audience validation")
}
if element == j.ClaimsToValidate["aud"] {
return nil
}
}
return fmt.Errorf("aud: %s does not match %s", v, j.ClaimsToValidate["aud"])
default:
return fmt.Errorf("unknown type for audience validation")
}
return nil
}
func (j *JwtVerifier) validateClientId(clientId interface{}) error {
// Client Id can be optional, it will be validated if it is present in the ClaimsToValidate array
if cid, exists := j.ClaimsToValidate["cid"]; exists && clientId != cid {
switch v := clientId.(type) {
case string:
if v != cid {
return fmt.Errorf("cid: %s does not match %s", v, cid)
}
case []string:
for _, element := range v {
if element == cid {
return nil
}
}
return fmt.Errorf("cid: %s does not match %s", v, cid)
default:
return fmt.Errorf("unknown type for clientId validation")
}
}
return nil
}
func (j *JwtVerifier) validateExp(exp interface{}) error {
expf, ok := exp.(float64)
if !ok {
return fmt.Errorf("exp: missing")
}
if float64(time.Now().Unix()-j.leeway) > expf {
return fmt.Errorf("the token is expired")
}
return nil
}
func (j *JwtVerifier) validateIat(iat interface{}) error {
iatf, ok := iat.(float64)
if !ok {
return fmt.Errorf("iat: missing")
}
if float64(time.Now().Unix()+j.leeway) < iatf {
return fmt.Errorf("the token was issued in the future")
}
return nil
}
func (j *JwtVerifier) validateIss(issuer interface{}) error {
if issuer != j.Issuer {
return fmt.Errorf("iss: %s does not match %s", issuer, j.Issuer)
}
return nil
}
func (j *JwtVerifier) getMetaData() (map[string]interface{}, error) {
metaDataUrl := j.Issuer + j.Discovery.GetWellKnownUrl()
value, err := j.metadataCache.Get(metaDataUrl)
if err != nil {
return nil, err
}
metadata, ok := value.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unable to cast %v to metadata", value)
}
return metadata, nil
}
func (j *JwtVerifier) isValidJwt(jwt string) (bool, error) {
if jwt == "" {
return false, errors.JwtEmptyStringError()
}
// Verify that the JWT Follows correct JWT encoding.
jwtRegex := regx.MatchString
if !jwtRegex(jwt) {
return false, fmt.Errorf("token must contain at least 1 period ('.') and only characters 'a-Z 0-9 _'")
}
parts := strings.Split(jwt, ".")
header := parts[0]
header = padHeader(header)
headerDecoded, err := base64.StdEncoding.DecodeString(header)
if err != nil {
return false, fmt.Errorf("the tokens header does not appear to be a base64 encoded string")
}
var jsonObject map[string]interface{}
isHeaderJson := json.Unmarshal([]byte(headerDecoded), &jsonObject) == nil
if !isHeaderJson {
return false, fmt.Errorf("the tokens header is not a json object")
}
_, algExists := jsonObject["alg"]
_, kidExists := jsonObject["kid"]
if !algExists {
return false, fmt.Errorf("the tokens header must contain an 'alg'")
}
if !kidExists {
return false, fmt.Errorf("the tokens header must contain a 'kid'")
}
if jsonObject["alg"] != "RS256" {
return false, fmt.Errorf("the only supported alg is RS256")
}
return true, nil
}
func padHeader(header string) string {
if i := len(header) % 4; i != 0 {
header += strings.Repeat("=", 4-i)
}
return header
}