forked from okta/okta-jwt-verifier-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwtverifier.go
318 lines (251 loc) · 8.1 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
/*******************************************************************************
* Copyright 2018 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"
"github.com/okta/okta-jwt-verifier-golang/adaptors"
"github.com/okta/okta-jwt-verifier-golang/adaptors/lestrratGoJwx"
"github.com/okta/okta-jwt-verifier-golang/discovery"
"github.com/okta/okta-jwt-verifier-golang/discovery/oidc"
"github.com/okta/okta-jwt-verifier-golang/errors"
"github.com/patrickmn/go-cache"
"net/http"
"regexp"
"strings"
"sync"
"time"
)
var metaDataCache *cache.Cache = cache.New(5*time.Minute, 10*time.Minute)
var metaDataMu = &sync.Mutex{}
type JwtVerifier struct {
Issuer string
ClaimsToValidate map[string]string
Discovery discovery.Discovery
Adaptor adaptors.Adaptor
leeway int64
}
type Jwt struct {
Claims map[string]interface{}
}
func (j *JwtVerifier) New() *JwtVerifier {
// Default to OIDC discovery if none is defined
if j.Discovery == nil {
disc := oidc.Oidc{}
j.Discovery = disc.New()
}
// Default to LestrratGoJwx Adaptor if none is defined
if j.Adaptor == nil {
adaptor := lestrratGoJwx.LestrratGoJwx{}
j.Adaptor = adaptor.New()
}
// Default to PT2M Leeway
j.leeway = 120
return j
}
func (j *JwtVerifier) SetLeeway(seconds int64) {
j.leeway = seconds
}
func (j *JwtVerifier) VerifyAccessToken(jwt string) (*Jwt, error) {
validJwt, err := j.isValidJwt(jwt)
if validJwt == false {
return nil, fmt.Errorf("token is not valid: %s", err.Error())
}
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. %s", err.Error())
}
err = j.validateAudience(token["aud"])
if err != nil {
return &myJwt, fmt.Errorf("the `Audience` was not able to be validated. %s", err.Error())
}
err = j.validateClientId(token["cid"])
if err != nil {
return &myJwt, fmt.Errorf("the `Client Id` was not able to be validated. %s", err.Error())
}
err = j.validateExp(token["exp"])
if err != nil {
return &myJwt, fmt.Errorf("the `Expiration` was not able to be validated. %s", err.Error())
}
err = j.validateIat(token["iat"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issued At` was not able to be validated. %s", err.Error())
}
return &myJwt, nil
}
func (j *JwtVerifier) decodeJwt(jwt string) (interface{}, error) {
metaData, err := j.getMetaData()
if err != nil {
return nil, err
}
resp, err := j.Adaptor.Decode(jwt, metaData["jwks_uri"].(string))
if err != nil {
return nil, fmt.Errorf("could not decode token: %s", err.Error())
}
return resp, nil
}
func (j *JwtVerifier) VerifyIdToken(jwt string) (*Jwt, error) {
validJwt, err := j.isValidJwt(jwt)
if validJwt == false {
return nil, fmt.Errorf("token is not valid: %s", err.Error())
}
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. %s", err.Error())
}
err = j.validateAudience(token["aud"])
if err != nil {
return &myJwt, fmt.Errorf("the `Audience` was not able to be validated. %s", err.Error())
}
err = j.validateExp(token["exp"])
if err != nil {
return &myJwt, fmt.Errorf("the `Expiration` was not able to be validated. %s", err.Error())
}
err = j.validateIat(token["iat"])
if err != nil {
return &myJwt, fmt.Errorf("the `Issued At` was not able to be validated. %s", err.Error())
}
err = j.validateNonce(token["nonce"])
if err != nil {
return &myJwt, fmt.Errorf("the `Nonce` was not able to be validated. %s", err.Error())
}
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 != 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 {
if audience != j.ClaimsToValidate["aud"] {
return fmt.Errorf("aud: %s does not match %s", audience, j.ClaimsToValidate["aud"])
}
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 {
return fmt.Errorf("clientId: %s does not match %s", clientId, cid)
}
return nil
}
func (j *JwtVerifier) validateExp(exp interface{}) error {
if float64(time.Now().Unix()-j.leeway) > exp.(float64) {
return fmt.Errorf("the token is expired")
}
return nil
}
func (j *JwtVerifier) validateIat(iat interface{}) error {
if float64(time.Now().Unix()+j.leeway) < iat.(float64) {
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()
metaDataMu.Lock()
defer metaDataMu.Unlock()
if x, found := metaDataCache.Get(metaDataUrl); found {
return x.(map[string]interface{}), nil
}
resp, err := http.Get(metaDataUrl)
if err != nil {
return nil, fmt.Errorf("request for metadata was not successful: %s", err.Error())
}
defer resp.Body.Close()
md := make(map[string]interface{})
json.NewDecoder(resp.Body).Decode(&md)
metaDataCache.SetDefault(metaDataUrl, md)
return md, nil
}
func (j *JwtVerifier) isValidJwt(jwt string) (bool, error) {
if jwt == "" {
return false, errors.JwtEmptyStringError()
}
// Verify that the JWT contains at least one period ('.') character.
var jwtRegex = regexp.MustCompile(`[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+\.?([a-zA-Z0-9-_]+)[/a-zA-Z0-9-_]+?$`).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 == false {
return false, fmt.Errorf("the tokens header is not a json object")
}
if len(jsonObject) < 2 {
return false, fmt.Errorf("the tokens header does not contain enough properties. " +
"Should contain `alg` and `kid`")
}
if len(jsonObject) > 2 {
return false, fmt.Errorf("the tokens header contains too many properties. " +
"Should only contain `alg` and `kid`")
}
_, algExists := jsonObject["alg"]
_, kidExists := jsonObject["kid"]
if algExists == false {
return false, fmt.Errorf("the tokens header must contain an 'alg'")
}
if kidExists == false {
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
}