forked from zhevron/jwt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
token.go
351 lines (299 loc) · 7.28 KB
/
token.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
package jwt
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/gostack/clock"
)
// Token contains the data structure of a JWT.
type Token struct {
Type Type
Algorithm Algorithm
KeyID string
JWTID string
Issuer string
Subject string
Audience string
IssuedAt time.Time
Expires time.Time
NotBefore time.Time
Claims map[string]interface{}
}
// NewToken creates a new Token struct using the default HS256 algorithm.
// IssuedAt is also initialized to the current UTC time.
func NewToken() *Token {
now := clock.Now().UTC()
return &Token{
Type: JWT,
Algorithm: HS256,
IssuedAt: now,
Claims: make(map[string]interface{}),
}
}
// DecodeToken attempts to decode a JWT into a Token structure using the given
// secret for verification. This function will only return an error if decoding
// fails or the signature is invalid.
//
// The secret parameter type is variable. All algorithms support string
// and []byte types, but some also have other custom types.
//
// Note: The "alg" field of the token header is completely ignored in order
// to ensure that a token is what the server expects.
func DecodeToken(token string, algorithm Algorithm, secret interface{}) (*Token, error) {
s := strings.Split(token, ".")
if len(s) != 3 {
return nil, ErrInvalidToken
}
t := NewToken()
if err := decodeHeader(t, s[0]); err != nil {
return nil, err
}
if err := decodePayload(t, s[1]); err != nil {
return nil, err
}
if keyLookupCallback != nil {
if len(t.KeyID) == 0 {
return nil, ErrNoKeyProvided
}
var key interface{}
algorithm, key = keyLookupCallback(t.KeyID)
if len(string(algorithm)) == 0 {
return nil, ErrNonExistantKey
}
if key != nil {
if _, ok := key.(string); !ok || (ok && len(key.(string)) > 0) {
secret = key
}
}
}
if algorithm != None {
tkn := fmt.Sprintf("%s.%s", s[0], s[1])
pair, ok := supportedAlgorithms[algorithm]
if !ok {
return nil, ErrUnsupportedAlgorithm
}
if err := pair.Verifier(tkn, s[2], secret); err != nil {
return nil, err
}
} else {
if secret != nil {
return nil, ErrNoneAlgorithmWithSecret
}
}
return t, nil
}
// decodeHeader attempts to decode the JWT header.
func decodeHeader(t *Token, s string) error {
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return err
}
header := make(map[string]interface{})
if err := json.Unmarshal(b, &header); err != nil {
return err
}
if v, ok := header["typ"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
if _, ok := supportedTypes[Type(v.(string))]; !ok {
return ErrUnsupportedTokenType
}
t.Type = Type(v.(string))
}
if v, ok := header["alg"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.Algorithm = Algorithm(v.(string))
}
if v, ok := header["kid"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.KeyID = v.(string)
}
return nil
}
// decodePayload attempts to decode the JWT payload.
func decodePayload(t *Token, s string) error {
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return err
}
payload := make(map[string]interface{})
if err := json.Unmarshal(b, &payload); err != nil {
return err
}
if v, ok := payload["jti"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.JWTID = v.(string)
}
if v, ok := payload["iss"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.Issuer = v.(string)
}
if v, ok := payload["sub"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.Subject = v.(string)
}
if v, ok := payload["aud"]; ok {
if _, ok := v.(string); !ok {
return ErrInvalidToken
}
t.Audience = v.(string)
}
if v, ok := payload["iat"]; ok {
if _, ok := v.(float64); !ok {
return ErrInvalidToken
}
t.IssuedAt = time.Unix(int64(v.(float64)), 0)
}
if v, ok := payload["nbf"]; ok {
if _, ok := v.(float64); !ok {
return ErrInvalidToken
}
t.NotBefore = time.Unix(int64(v.(float64)), 0)
}
if v, ok := payload["exp"]; ok {
if _, ok := v.(float64); !ok {
return ErrInvalidToken
}
t.Expires = time.Unix(int64(v.(float64)), 0)
}
for k, v := range payload {
if _, ok := reservedClaims[k]; ok {
continue
}
t.Claims[k] = v
}
return nil
}
// Sign signs the token with the provided secret and returns the base64 encoded
// string value of the token.
//
// The secret parameter type is variable. All algorithms support string
// and []byte types, but some also have other custom types.
// Refer to the documentation in each encryption package for the options.
func (t Token) Sign(secret interface{}) (string, error) {
header, err := json.Marshal(t.buildHeader())
if err != nil {
return "", err
}
claims, err := t.buildClaims()
if err != nil {
return "", err
}
payload, err := json.Marshal(claims)
if err != nil {
return "", err
}
tkn := fmt.Sprintf(
"%s.%s",
base64.RawURLEncoding.EncodeToString(header),
base64.RawURLEncoding.EncodeToString(payload),
)
signature := ""
if t.Algorithm != None {
pair, ok := supportedAlgorithms[t.Algorithm]
if !ok {
return "", ErrUnsupportedAlgorithm
}
signature, err = pair.Signer(tkn, secret)
if err != nil {
return "", err
}
}
return fmt.Sprintf(
"%s.%s",
tkn,
signature,
), nil
}
// Verify attempts to verify the token using the provided issuer, subject and
// audience. If either provided value is left empty, the value is skipped.
// Validity and expiration will also be checked.
func (t Token) Verify(issuer, subject, audience string, leeway time.Duration) error {
if len(issuer) > 0 && issuer != t.Issuer {
return ErrInvalidIssuer
}
if len(subject) > 0 && subject != t.Subject {
return ErrInvalidSubject
}
if len(audience) > 0 && audience != t.Audience {
return ErrInvalidAudience
}
if !t.Valid(leeway) {
return ErrTokenNotValidYet
}
if t.Expired(leeway) {
return ErrTokenExpired
}
return nil
}
// Valid checks if the token is valid yet.
func (t Token) Valid(leeway time.Duration) bool {
now := clock.Now().UTC()
nbf := t.NotBefore.Add(-leeway)
return nbf.Before(now)
}
// Expired checks if the token has expired.
func (t Token) Expired(leeway time.Duration) bool {
if t.Expires.IsZero() {
return false
}
if t.IssuedAt.Equal(t.Expires) {
return false
}
now := clock.Now().UTC()
exp := t.Expires.Add(leeway)
return now.After(exp)
}
// buildHeader builds a new header map ready for signing.
func (t Token) buildHeader() map[string]interface{} {
header := make(map[string]interface{})
header["typ"] = t.Type
header["alg"] = t.Algorithm
if len(t.KeyID) > 0 {
header["kid"] = t.KeyID
}
return header
}
// buildClaims builds a new claims map ready for signing.
func (t Token) buildClaims() (map[string]interface{}, error) {
claims := make(map[string]interface{})
if len(t.JWTID) > 0 {
claims["jti"] = t.JWTID
}
if len(t.Issuer) > 0 {
claims["iss"] = t.Issuer
}
if len(t.Subject) > 0 {
claims["sub"] = t.Subject
}
if len(t.Audience) > 0 {
claims["aud"] = t.Audience
}
claims["iat"] = t.IssuedAt.Unix()
if !t.NotBefore.IsZero() {
claims["nbf"] = t.NotBefore.Unix()
}
if !t.Expires.IsZero() {
claims["exp"] = t.Expires.Unix()
}
for k, v := range t.Claims {
if _, ok := reservedClaims[k]; ok {
return claims, ErrReservedClaim
}
claims[k] = v
}
return claims, nil
}